fork download
  1. import time
  2. import random
  3. import math
  4. from typing import *
  5.  
  6.  
  7. def newton(f, fder, x0, iteration_limit=1000, tolerance=1e-10) -> Tuple[float, int]:
  8. i = 0
  9. xn = x0
  10. xn_1 = x0
  11. while i < iteration_limit and not math.isclose(f(xn), 0, abs_tol=tolerance):
  12. xn = xn_1 - f(xn_1) / fder(xn_1)
  13. xn_1 = xn
  14. i += 1
  15. return (xn, i)
  16.  
  17.  
  18. def find_null_point(f, fder, x0) -> None:
  19. calculation_start = time.perf_counter()
  20. (null_point, iterations_needed) = newton(f, fder, x0)
  21. calculation_end = time.perf_counter()
  22. calculation_time = calculation_end - calculation_start
  23.  
  24. print("Newtons method result: {} (f(x): {}, iterations needed: {}, starting point: {}, time spent: {})".format(
  25. null_point, f(null_point), iterations_needed, x0, calculation_time))
  26.  
  27.  
  28. f = lambda x: x - 3
  29. fder = lambda x: 1
  30. g = lambda x: x**2 - 3
  31. gder = lambda x: 2 * x
  32. x0 = random.uniform(-100, 100) # start at random x0 point at x axis
  33. find_null_point(f, fder, x0)
  34. find_null_point(g, gder, x0)
Success #stdin #stdout 0.03s 12556KB
stdin
Standard input is empty
stdout
Newtons method result: 3.0 (f(x): 0.0, iterations needed: 1, starting point: 94.16773059053784, time spent: 1.1803116649389267e-05)
Newtons method result: 1.7320508075688774 (f(x): 4.440892098500626e-16, iterations needed: 10, starting point: 94.16773059053784, time spent: 1.0865973308682442e-05)