Root Finding
Root Finding
f = lambda x: x**2-2
r = optimize.fsolve(f, 1)
print(”r =”, r)
r = [1.41421356]
output= [-8.8817842e-16]
result = f(r)
print(”result=”, result)
print(mesg)
r = [-3.52047359e+83]
result= [-2.84052692e-84]
The number of calls to function has reached maxfev = 400.
import numpy as np
1
# get midpoint
m = (a + b)/2
if np.abs(f(m)) < tol:
# stopping condition, report m as root
return m
elif np.sign(f(a)) == np.sign(f(m)):
# case where m is an improvement on a.
# Make recursive call with a = m
return my_bisection(f, m, b, tol)
elif np.sign(f(b)) == np.sign(f(m)):
# case where m is an improvement on b.
# Make recursive call with b = m
return my_bisection(f, a, m, tol)
f = lambda x: x**2-2
r1 = my_bisection(f,0,2,0.1)
print(”r1 = ”, r1)
print(”f(r1) = ”, f(r1))
r2 = my_bisection(f,0,2,0.01)
print(”\nr2 = ”, r2)
print(”f(r2) = ”, f(r2))
r1 = 1.4375
f(r1) = 0.06640625
r2 = 1.4140625
f(r2) = -0.00042724609375
f = lambda x: x**2 - 2
f_prime = lambda x: 2*x
newton_raphson = 1.4142857142857144
sqrt(2) = 1.4142135623730951
[6]: # fsolve
2
f = lambda x: x**3-100*x**2-x+100
#fsolve(f,x0)
fsolve(f, [2, 80])
[ ]: