Tuesday, May 10, 2011

How to find the intersection of two functions

Previously we have seen how to find roots of a function with fsolve, in this example we use fsolve to find an intersection between two functions, sin(x) and cos(x):
from scipy.optimize import fsolve
import pylab
import numpy

def findIntersection(fun1,fun2,x0):
 return fsolve(lambda x : fun1(x) - fun2(x),x0)

result = findIntersection(numpy.sin,numpy.cos,0.0)
x = numpy.linspace(-2,2,50)
pylab.plot(x,numpy.sin(x),x,numpy.cos(x),result,numpy.sin(result),'ro')
pylab.show()
In the graph we can see sin(x) (blue), cos(x) (green) and the intersection found (red dot) starting from x = 0.

Monday, May 9, 2011

How to find the roots of a function with fsolve

The function fsolve provided by numpy return the roots of the (non-linear) equations defined by func(x) = 0 given a starting estimate. We will see how to use fsolve to find the root of the function

from scipy.optimize import fsolve
import pylab
import numpy

pow3 = lambda x : x**3

result = fsolve(pow3,10) # starting from x = 10
print result
x = numpy.linspace(-1,1,50)
pylab.plot(x,pow3(x),result,pow3(result),'ro')
pylab.grid(b=1)
pylab.show()
In the following graph we can see f(x) (blue curve) and the solution found (red dot)

Friday, May 6, 2011

How to use string's Template

Templates provide simple string substitutions mechanism, here's a simple demonstration:
from string import Template

template = Template('The president of $state is $name')
message = template.substitute(state='USA', name='Obama')
print '1.',message
message = template.substitute(state='France', name='Sarkozy')
print '2.',message

try:
 # will raise an exception
 message = template.substitute(state='England')
except Exception as e:
 print 'I cannot fill the placeholder',e
 #  original name placeholder will be used
 message = template.safe_substitute(state='England') 

print '3.',message
The output of this script will be
1. The president of USA is Obama
2. The president of France is Sarkozy
I cannot fill the placeholder 'name'
3. The president of England is $name