mirror of
https://github.com/TheAlgorithms/Python.git
synced 2025-02-25 02:18:39 +00:00
Compare commits
7 Commits
7b7a149b06
...
27b1bbacb6
Author | SHA1 | Date | |
---|---|---|---|
|
27b1bbacb6 | ||
|
064bc8cb88 | ||
|
aeb42b1e12 | ||
|
cc3d6a62fc | ||
|
cbaeaa035c | ||
|
8d6f837303 | ||
|
daf594dd50 |
@ -1,7 +1,8 @@
|
|||||||
# 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
|
||||||
@ -19,7 +20,22 @@ 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")
|
||||||
|
|
||||||
@ -38,7 +54,7 @@ def newton_raphson(
|
|||||||
if abs(function_value) < precision:
|
if abs(function_value) < precision:
|
||||||
return float(x)
|
return float(x)
|
||||||
|
|
||||||
x = x - (function_value / derivative_value)
|
x -= function_value / derivative_value
|
||||||
|
|
||||||
return float(x)
|
return float(x)
|
||||||
|
|
||||||
|
Loading…
x
Reference in New Issue
Block a user