Integrals
p39 Finding the functions from derivatives is called integration.
""" Antidifferention or Integration
It means getting the original function from derived function.
Integration can be used to find areas, volumes, central points
and many other useful things.
Function: f = 3x + 2
Derived: d = 3
Integral: I = 3x
y' = ax then y = (ax^2)/2 + C
y = ax + b then y = (ax^2)/2 + bx + C
"""
import numpy as np
import matplotlib.pyplot as plt
from sympy import *
import scipy.integrate as spi
x = Symbol('x')
t = Symbol('t')
# Symbolic representation
f = 3*x + 2
d = f.diff(x)
I = integrate(d, x)
print('Derivative =', d) # Derivative = 3
print('Integral =', I) # Integral = 3*x
print()
s = 16*t**2
d = s.diff(t)
I = integrate(d, t)
print('Derivative =', d) # Derivative = 32*t
print('Integral =', I) # Integral = 16*t**2
# Integral value
def f(x):
return 3*x + 2
A, err = spi.quad(f, 0, 1)
print('Integral = ', A) # Integral = 3.5
def s(t):
return 16*t**2
A2, err = spi.quad(s, 0, 1)
print('Integral = ', A2) # Integral = 5.333333333333334
# Plotting
x = np.linspace(0, 1, 100)
y = f(x)
fig, ax = plt.subplots()
ax.plot(x, y, label="f(x) = 3x + 2")
ax.fill_between(x, y, 0, where=(x >= 0) & (x <= 1), color="gray", alpha=0.5,
label=f'Integral (Area) = %s' %A)
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.legend()
plt.show()

Definite integral
A definite integral has start and end values.
""" Calcutate definite integrals
A definite integral has start and end values [a, b]
The symbol for integral is a stylish S from sum, or summing slices
"""
import numpy as np
import scipy.integrate as spi
import matplotlib.pyplot as plt
# Function to be integrated
def f(x):
return x**2
def integral_approximation_A(Y, a, b): # numpy
approx = (b-a) * np.mean(Y)
return approx
def integral_approximation_B(f, a, b): #scipy
approx, error = spi.quad(f, a, b)
return approx
# Integral bounds
a = 0
b = 1
# Function values
range = np.arange(a, b + .0001, .0001)
Y = f(range)
# Integral approximation
approx_A = integral_approximation_A(Y, a, b) # numpy
approx_B = integral_approximation_B(f, a, b) # scipy
print(approx_A) # 0.33335
print(approx_B) # 0.33333333333333337
# Plotting the function
x = np.linspace(0, 1, 100)
y = f(x)
fig, ax = plt.subplots()
ax.plot(x, y, label="f(x) = x^2")
ax.fill_between(x, y, 0, where=(x >= 0) & (x <= 1), color="gray", alpha=0.5,
label=f'I = %s' %round(approx_B, 4))
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.legend()
plt.show()

Gaussian function
Integrating the standard Gaussian distribution.
""" Gausssian distribution
Calculate integral for gaussian functions
We use scipy approximation
PDF, probability distribution function
Gaussian distribution is also called normal distribution
The definitive integral of a function gives
the total area under the curve function over an interval (a, b)
"""
import numpy as np
import matplotlib.pyplot as plt
import scipy.integrate as integrate
import scipy.stats as stats
# Gaussian function
def gaussian(x, mu, sigma):
return np.exp((-1*(x - mu)**2) / (2 * sigma**2))
# Define mu and sigma
mu = 0
sigma = 1
# axis for plot
X = np.arange(-5, 5, 0.001)
Y = stats.norm.pdf(X, mu, sigma) # calculates PDF for normal distribution
# Define bounds of integral
a = -3
b = 3
# Integral approximation (area)
approx, error = integrate.quad(
lambda x: gaussian(x, mu, sigma), a, b
)
print(approx)
# 2.4998608894830947
plt.plot(X, Y, label="Gaussian distribution")
plt.fill_between(X, Y, 0, where=(X >= a) & (X <= b), color='gray', alpha=0.5,
label=f'I = %s' %round(approx, 4))
plt.legend()
plt.show()

Falling object (A)
p42 Use antidifferentiation to get distance traveled from acceleration.
""" Object Free fall
What is the time in which an object dropped
from a 400ft point reaches earth (in the absence of air)
t = ?
Galileo: An object fall to earth with the same acceleration
a = 32 ft/s^2
a = 9.8 m/s^2
Acceleration is the instantaneus rate of change of speed / time
v' = 32
v = 32t + C
v = 32t (object is dropped, zero speed at start)
Instantaneus speed is the rate of change of distance / time
s' = 32t
s = 16t^2 + C
s = 16t^2
To answer the initial question, 400ft fall
400 = 16t^2
t = [-5, 5]
t = 5 (because we have downward fall)
By antidifferentiation we can proceed from acceleration to speed,
and from acceleration to the distance traveled
a = 32
v = a'
s = a''
Distance traveled in 5 seconds is 400
t = 5
s = 400
"""
# ---------------------------------------------------------
# Symbolic representation
import numpy as np
from sympy import *
t = Symbol('t')
a = 32
v = integrate(a, t)
s = integrate(v, t)
print('Acceleration =', a) # Acceleration = 32
print('Speed =', v) # Speed = 32*t
print('Distance =', s) # Distance = 16*t**2
# Distance traveled in 5 seconds
distance = s.subs(t, 5)
print("Distance =", distance) # 400
# Time for 400ft fall
s = s - 400 # s = 16*t**2 - 400
time = solve(s, t) # find the value of t that makes s = 0
print("Time =", time[1]) # 5
# ---------------------------------------------------------
# Plotting
import matplotlib.pyplot as plt
t = np.linspace(0, 6)
s = 16*t**2
fig, ax = plt.subplots()
ax.plot(t, s, label="s(t) = 16t^2")
ax.set_xlabel("t")
ax.set_ylabel("s(t)")
ax.legend()
plt.scatter(5, 400, label="s(5) = 400")
plt.plot((5, 5), (0, 400), linestyle='--')
plt.plot((0, 5), (400, 400), linestyle='--')
plt.show()
# ---------------------------------------------------------
# Animation
from matplotlib.animation import FuncAnimation
def update(frame):
t = np.linspace(0, frame/10)
s = 16 * t**2
ax.clear()
ax.plot(t, s)
ax.set_xlabel("t")
ax.set_ylabel("s(t)")
ax.set_ylim(400, 0)
ax.set_xlim(0, 5.2)
ax.set_title("s(t) = 16t^2")
y = 16*(frame/10)**2
ax.scatter(5, y, label="s(t) = 400 - 16t^2")
ax.plot((frame/10, frame/10), (5, y), linestyle='--')
ax.plot((5, frame/10), (y, y), linestyle='--')
fig, ax = plt.subplots()
ani = FuncAnimation(fig, update, frames=np.arange(10, 51, 1), repeat=True)
plt.show()
# ani.save('1427_falling_ball.gif', writer='imagemagick', fps=10)


Thrown down (A)
p44 When the object is trown down it has an starting velocity.
""" Object thrown downward
When the object leaves the hand it already has some velocity
Suppose, for example, that the velocity is 100 ft/sec
a = 32
v = 32t + C; 100 = 32 * 0 + C; C = 100
v = 32t + 100
s' = 16t^2 + 100t + C
Let us agree that the distance is measured from the release point
t = 0; s = 0; C = 0
s = 16t^2 + 100t
Distance traveled in 5 seconds is 400
t = 5
s = 900
"""
# ---------------------------------------------------------
# Symbolic representation
import numpy as np
from sympy import *
t = Symbol('t')
a = 32
v = integrate(a, t) + 100 # Look Hee
s = integrate(v, t)
print('Acceleration =', a) # 32
print('Speed =', v) # 32*t + 100
print('Distance =', s) # 16*t**2 + 100*t
# Distance after 5 sec
distance = s.subs(t, 5)
print("Distance =", distance) # 900
# Distance after 2.77 sec
distance = s.subs(t, 2.77)
print("Distance =", distance) # 400
# Time for 400ft thrown fall
s = s - 400 # s = 16*t**2 + 100t
time = solve(s, t) # resolve equation that makes s = 0
print("Time =", round(time[0], 2)) # 3
# ---------------------------------------------------------
# Plotting
import matplotlib.pyplot as plt
t = np.linspace(0, 5)
s = 16*t**2 + 100*t
fig, ax = plt.subplots()
ax.plot(t, s, label="s(t) = 16t^2 + 100t")
ax.set_xlabel("t")
ax.set_ylabel("s(t)")
ax.legend()
plt.scatter(2.77, 400, label="s(.277) = 400")
plt.plot((2.77, 2.77), (0, 400), linestyle='--')
plt.plot((0, 2.77), (400, 400), linestyle='--')
plt.show()
# ---------------------------------------------------------
# Animation
from matplotlib.animation import FuncAnimation
def update(frame):
t = np.linspace(0, frame/10)
s = 16 * t**2 + 100*t
ax.clear()
ax.plot(t, s)
ax.set_xlabel("t")
ax.set_ylabel("s(t)")
ax.set_ylim(400, 0)
ax.set_xlim(0, 5.2)
ax.set_title("s(t) = 16t^2 + 100t")
y = 16*(frame/10)**2 + 100*(frame/10)
ax.scatter(2.77, y, label="s(t) = 400 - (16t^2 + 100t)")
ax.plot((frame/10, frame/10), (2.77, y), linestyle='--')
ax.plot((2.77, frame/10), (y, y), linestyle='--')
fig, ax = plt.subplots()
ani = FuncAnimation(fig, update, frames=np.arange(10, 29, 1), repeat=False)
plt.show()
# ani.save('1427_throw_ball.gif', writer='imagemagick', fps=10)


➥ Questions
Last update: 48 days ago