Root Finding
| categories: Transcripts
Today we talked about finding the zeros (roots) of a function.
We used this function as an example.
def f(x):
return np.sin(10*x) - x**3 + 1
In class we came up with a function like this:
def trapZero(f, x0, x1):
if f(x0) > 0:
x0,x1 = x1,x0 # swap so f(x0) is the negative one
while abs(x0 - x1) > 1e-6:
xm = (x0 + x1) / 2.0 # compute the midpoint
fm = f(xm) # evaluate the function at the midpoint
if np.sign(fm) == -1: # close in on the root from the negative side
x0 = xm
elif np.sign(fm) == 1: # close in on the root from the positive side
x1 = xm
elif np.sign(fm) == 0: # we happened to hit it (very rare)
return xm
return (x0 + x1) / 2.0 # why didn't I return xm?