Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Newton's method
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
==Code== The following is an example of a possible implementation of Newton's method in the [[Python (programming language)|Python]] (version 3.x) programming language for finding a root of a function <code>f</code> which has derivative <code>f_prime</code>. The initial guess will be {{math|1={{var|x}}{{sub|0}} = 1}} and the function will be {{math|1={{var|f}}({{var|x}}) = {{var|x}}{{sup|2}} β 2}} so that {{math|1={{var|{{prime|f}}}}({{var|x}}) = 2{{var|x}}}}. Each new iteration of Newton's method will be denoted by <code>x1</code>. We will check during the computation whether the denominator (<code>yprime</code>) becomes too small (smaller than <code>epsilon</code>), which would be the case if {{math|{{var|{{prime|f}}}}({{var|x}}{{sub|{{var|n}}}}) β 0}}, since otherwise a large amount of error could be introduced. <syntaxhighlight lang="python3" line="1"> def f(x): return x**2 - 2 # f(x) = x^2 - 2 def f_prime(x): return 2*x # f'(x) = 2x def newtons_method(x0, f, f_prime, tolerance, epsilon, max_iterations): """Newton's method Args: x0: The initial guess f: The function whose root we are trying to find f_prime: The derivative of the function tolerance: Stop when iterations change by less than this epsilon: Do not divide by a number smaller than this max_iterations: The maximum number of iterations to compute """ for _ in range(max_iterations): y = f(x0) yprime = f_prime(x0) if abs(yprime) < epsilon: # Give up if the denominator is too small break x1 = x0 - y / yprime # Do Newton's computation if abs(x1 - x0) <= tolerance: # Stop when the result is within the desired tolerance return x1 # x1 is a solution within tolerance and maximum number of iterations x0 = x1 # Update x0 to start the process again return None # Newton's method did not converge </syntaxhighlight>
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)