Compare commits

..

No commits in common. "27b1bbacb69b6370c3dd217e5a2dc4835971b579" and "7b7a149b068435d4b9a99c0907d31da6997abfad" have entirely different histories.

View File

@ -1,8 +1,7 @@
# Implementing Newton Raphson method in Python # Implementing Newton Raphson method in Python
# Author: Syed Haseeb Shah (github.com/QuantumNovice) # Author: Syed Haseeb Shah (github.com/QuantumNovice)
# The Newton-Raphson method (also known as Newton's method) is a way to # The Newton-Raphson method (also known as Newton's method) is a way to
# quickly find a good approximation for the root of a real-valued function. # quickly find a good approximation for the root of a real-valued function
# https://en.wikipedia.org/wiki/Newton%27s_method
from __future__ import annotations from __future__ import annotations
from sympy import diff, symbols, sympify from sympy import diff, symbols, sympify
@ -20,22 +19,7 @@ def newton_raphson(
2.23606797749979 2.23606797749979
>>> newton_raphson("log(x)- 1", 2) >>> newton_raphson("log(x)- 1", 2)
2.718281828458938 2.718281828458938
>>> from scipy.optimize import newton
>>> all(newton_raphson("log(x)- 1", 2) == newton("log(x)- 1", 2)
... for precision in (10, 100, 1000, 10000))
True
>>> newton_raphson("log(x)- 1", 2, 0)
Traceback (most recent call last):
...
ValueError: precision must be greater than zero
>>> newton_raphson("log(x)- 1", 2, -1)
Traceback (most recent call last):
...
ValueError: precision must be greater than zero
""" """
if precision <= 0:
raise ValueError("precision must be greater than zero")
x = start_point x = start_point
symbol = symbols("x") symbol = symbols("x")
@ -54,7 +38,7 @@ def newton_raphson(
if abs(function_value) < precision: if abs(function_value) < precision:
return float(x) return float(x)
x -= function_value / derivative_value x = x - (function_value / derivative_value)
return float(x) return float(x)