Advertisement
Guest User

Root Finder

a guest
Apr 6th, 2020
169
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.43 KB | None | 0 0
  1. #-------------------------------------------------------------------------------
  2. # Name:        RootFinder.py
  3. #
  4. # Author:      Arjol Panci
  5. #
  6. # Created:     05-04-2020
  7. #-------------------------------------------------------------------------------
  8. import math
  9.  
  10. def falsePosition(xu, xl, fxu, fxl):
  11.     return xu - ((fxu)*(xl-xu))/(fxl-fxu)
  12.  
  13. def findRootFalsePosition(f, xu, xl):
  14.     fxu = f(xu)
  15.     fxl = f(xl)
  16.     xr = falsePosition(xu, xl, fxu, fxl)
  17.     fxr = f(xr)
  18.     while abs(fxr) > 0.00001:
  19.         xr = falsePosition(xu, xl, fxu, fxl)
  20.         fxr = f(xr)
  21.         if abs(fxr) < 0.00001:
  22.             return xr
  23.         if ((fxr>0 and fxu>0) or (fxr<0 and fxu<0)):
  24.             xu = xr
  25.             fxu = fxr
  26.         elif ((fxr>0 and fxl>0) or (fxr<0 and fxl<0)):
  27.             xl = xr
  28.             fxl = fxr
  29.     return xr
  30.  
  31. def findRootNewton(f, x0):
  32.     fx0 = f(x0)
  33.     while(abs(fx0) > 0.00001):
  34.         x0 = x0 - (fx0/derivativeApprox(x0, 0.0000000001, f))
  35.         fx0 = f(x0)
  36.     return x0
  37.  
  38. def derivativeApprox(x, dx, f):
  39.     return (f(x+dx) - f(x))/(dx)
  40.  
  41. def f(x):
  42.     return x**2-1 + math.log(x+1)
  43.  
  44. def f2(x):
  45.     return math.log(1+x)*math.sin(x) + x**3 + 2*(x**2) - x - 2
  46.  
  47. def f3(x):
  48.     a = (x)*((1+x)**35)
  49.     return 24/x - 24/a - 140
  50.  
  51. print(findRootFalsePosition(f, 0, 1))
  52. print(findRootNewton(f, 1))
  53. print(findRootFalsePosition(f2, 0, 1))
  54. print(findRootNewton(f2, 1))
  55.  
  56. print(findRootNewton(f3, 0.16))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement