Advertisement
B1KMusic

root calculator

Nov 11th, 2018
323
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.55 KB | None | 0 0
  1. # cbrt(x) = n such that n^3 = x
  2. # n^3 = x
  3. # n^3 - x = 0
  4. # f(n) = n^3 - x
  5. # f'(n) = 3n^2
  6. # g(n) = n - (f(n)/f'(n))
  7. # cbrt(x) = (approx) g^10(1) where x = x in all above functions
  8. # we can generalize this to other 1/x exponents
  9.  
  10. def root(e, x):
  11.     f  = lambda g: g**e - float(x)
  12.     fp = lambda g: e * g**(e-1)
  13.     g  = lambda g: g - f(g) / fp(g)
  14.     guess = 1.0
  15.  
  16.     for i in range(10):
  17.         guess = g(guess)
  18.  
  19.     return guess
  20.  
  21. # example usage: root(4, 3) calculates the 4th root of 3 (n where n*n*n*n = 3)
  22. #                ~1.316074012952492
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement