The idea is we started from x=0 and walking to the positive direction and evaluating f(x) as we walk.
If there's change of the sign of f(x) from + to -, or vice versa, there must be a root in that area.
We began to surround it to find the-x that correspond to f(x)=0. That x value is the root.
After the root is found, we began to walk along x-axis again until found any sign change of f(x), or until x limit set on code.
Here's the code, I use Pythonista on my iPad and, because I use cosine function, I got several root value.
import numpy as np def f(x): return np.cos(x) def findRoot(xa,xb): if f(xa)==0: print 'the root is a ', xa if f(xb)==0: print 'the root is b ', xb xc = (xa+xb)/2. while f(xc)>abs(1./64.): if f(xc)*f(xa)>0: xa = xc else: xb = xc xc = (xa+xb)/2. print 'the root is', xc limit = 10 dx = 1./8. xa = 0. xb = 0. while xb<limit: xb += dx if (f(xa)*f(xb)<0): print xa, f(xa), f(xb) findRoot(xa,xb) xa = xb
No comments:
Post a Comment