# How to integrate a function using python ?

Published: February 09, 2019

To integrate a function using python, a solution is ti use the scipy method quad. Example, let's try to integrate the function

f: x\rightarrow cos(x)

between $0$ andt $\frac{9\pi}{2}$.

import numpy as np

xmin = 0.0
xmax = 9.0 * ( np.pi / 2.0 )

def function(x):
return np.cos(x)

res, err = quad(function, xmin, xmax)
print 'norm: ', res

Example using matplotlib

from pylab import *

import numpy as np

xmin = 0.0
xmax = 9.0 * ( np.pi / 2.0 )

def function(x):
return np.cos(x)

res, err = quad(function, xmin, xmax)
print 'norm: ', res

t = arange(xmin, xmax, 0.01)

ax = subplot(111)
ax.plot(t, function(t),'r-')

ax.grid(True)

ax.set_xlim(xmin,xmax)
ax.set_ylim(-1.25,1.25)

ax.fill_between(t, 0, function(t))

plt.savefig('IntegraleSimplePython.png')
show()

It is possible to integrate a function that takes several parameters with quad in python, example of syntax for a function f that takes two arguments: arg1 and arg2:

Example of code using quad with a function that takes multiple arguments:

import matplotlib.pyplot as plt
import scipy.stats
import numpy as np

def normal_distribution_function(x,mean,std):
value = scipy.stats.norm.pdf(x,mean,std)
return value

x_min = 0.0
x_max = 30.0

mean = 15.0
std = 4.0

ptx = np.linspace(x_min, x_max, 100)
pty = scipy.stats.norm.pdf(ptx,mean,std)

plt.plot(ptx,pty, color='gray')

plt.fill_between(ptx, pty, color='#e1b1b4', alpha='1.0')

plt.grid()

plt.title('How to integrate a function that takes parameteres in python ?', fontsize=10)
plt.xlabel('x', fontsize=8)
plt.ylabel('Probability Density Function', fontsize=8)

res, err = quad(normal_distribution_function, x_min, x_max, args=(mean,std,))

print(res)

plt.savefig("integrate_function_takes_parameters.png")
plt.show()

Image

of