Simple example of how to integrate a function
More information:
http://docs.scipy.org/doc/scipy/reference/generated/scipy.integrate.quad.html
In [60]:
import scipy.integrate as spi
import numpy as np
import matplotlib.pylab as plt
In [61]:
%matplotlib inline
In [9]:
def f(x):
return x**2
Compute the definite integral
In [15]:
spi.quad(f, 0, 4)
#-- It returns a tuple with the result and the error
Out[15]:
In [18]:
#--- The exact result is:
4 ** 3 / 3.
Out[18]:
Function to be integrated: $ g(x) = A \sin ( \frac{2 \pi k}{T} + \phi) $
In [63]:
##-- Function with one variable and three constants
def g(x, A = 1., k = 1, T = 1., phi = 0):
#-- This is just for debugging
print("A: {}, k:{}, T:{}, phi:{}".format(A, k, T, phi))
#-- The function
return A * np.sin(2 * np.pi * k * x / T + phi)
In [53]:
g(1/4.)
Out[53]:
In [54]:
g(0)
Out[54]:
In [67]:
x = np.linspace(0, 1, 50)
plt.plot(x, g(x), linewidth = 2)
plt.axis([0, 1, -1.1, 1.1])
plt.grid()
plt.show()
In [69]:
#-- Integrate the function
spi.quad(g, a = 0, b = 1/2.)
Out[69]:
In [71]:
spi.quad(g, a = 0, b = 1)
Out[71]:
In [73]:
x = np.linspace(0, 1, 50)
plt.plot(x, g(x, k = 2), linewidth = 2)
plt.axis([0, 1, -1.1, 1.1])
plt.grid()
plt.show()
In [75]:
spi.quad(g, a = 0, b = 1/4., args = (1, 2) ) #-- k = 2
Out[75]:
TODO: Calculate the real integral and check that these results are ok