A standard mathematical process is integrating an equation. SciPy accomplishes this using a callback function to iteratively calculate out the integration of your function. For example, suppose that we wanted to determine the integral of the following equation:
We would use a script like the following. We are using the definition of pi from the standard math package.
from scipy.integrate import quad import math def integrand(x, a, b): return a*math.pi + b a = 2 b = 1 quad(integrand, 0, 1, args=(a,b))
Again, this coding is very clean and simple, yet almost impossible to do in many languages. Running this script in Jupyter we see the results quickly:
I was curious how the integrand function is used during the execution. I am using this to exercise a call back function. To see this work, I added some debugging information to the script where we count how many iterations occur and what display the values called each time:
from scipy.integrate import quad import math counter = 0 def integrand(x, a, b): global counter counter = counter + 1 print ('called with x=',x,'a = ',a,'b = ', b) return a*math.pi + b a = 2 b = 1 print(quad(integrand, 0, 1, args=(a,b)))
print(counter)
We are using a counter at the global level, hence when referencing inside the integrand function we use the global keyword. Otherwise, Python assumes it is a local variable to the function.
The results are as follows:
The function was called 21 times to narrow down the solution.