# Example of how to do some basic numerical calculations using Python and SciPy # by Dan Schroeder, January 2013 # To run this program you need a Python installation that includes SciPy. # I recommend the EPD free distribution from Enthought, www.enthought.com. # Import libraries for general math and the SciPy stuff we'll use: import math, scipy.integrate, scipy.optimize # Define a function to integrate: def integrand(x): return (x**2) * math.exp(-x**2) # Use the quad function to do the integral; limits are from 0 to 0.5: (result, error) = scipy.integrate.quad(lambda x: integrand(x), 0, 0.5) print 'The integral is', result, '+/-', error # Now define a function with a nontrivial zero: def functionwithroot(x): return math.tanh(x) - x/2 # Use the brentq function to find where the function is zero between x=1 and 2: result = scipy.optimize.brentq(lambda x: functionwithroot(x), 1, 2) print 'The root is at x =', result