Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #-------------------------------------------------------------------------------
- # Name: RootFinder.py
- #
- # Author: Arjol Panci
- #
- # Created: 05-04-2020
- #-------------------------------------------------------------------------------
- import math
- def falsePosition(xu, xl, fxu, fxl):
- return xu - ((fxu)*(xl-xu))/(fxl-fxu)
- def findRootFalsePosition(f, xu, xl):
- fxu = f(xu)
- fxl = f(xl)
- xr = falsePosition(xu, xl, fxu, fxl)
- fxr = f(xr)
- while abs(fxr) > 0.00001:
- xr = falsePosition(xu, xl, fxu, fxl)
- fxr = f(xr)
- if abs(fxr) < 0.00001:
- return xr
- if ((fxr>0 and fxu>0) or (fxr<0 and fxu<0)):
- xu = xr
- fxu = fxr
- elif ((fxr>0 and fxl>0) or (fxr<0 and fxl<0)):
- xl = xr
- fxl = fxr
- return xr
- def findRootNewton(f, x0):
- fx0 = f(x0)
- while(abs(fx0) > 0.00001):
- x0 = x0 - (fx0/derivativeApprox(x0, 0.0000000001, f))
- fx0 = f(x0)
- return x0
- def derivativeApprox(x, dx, f):
- return (f(x+dx) - f(x))/(dx)
- def f(x):
- return x**2-1 + math.log(x+1)
- def f2(x):
- return math.log(1+x)*math.sin(x) + x**3 + 2*(x**2) - x - 2
- def f3(x):
- a = (x)*((1+x)**35)
- return 24/x - 24/a - 140
- print(findRootFalsePosition(f, 0, 1))
- print(findRootNewton(f, 1))
- print(findRootFalsePosition(f2, 0, 1))
- print(findRootNewton(f2, 1))
- print(findRootNewton(f3, 0.16))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement