From 6914d483a12a5eb28be8c09aa7465ead2be9a622 Mon Sep 17 00:00:00 2001 From: neingeist Date: Mon, 3 Nov 2014 18:36:04 +0100 Subject: [PATCH] Newton's method --- newtons-method.py | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 newtons-method.py diff --git a/newtons-method.py b/newtons-method.py new file mode 100644 index 0000000..9f7aff9 --- /dev/null +++ b/newtons-method.py @@ -0,0 +1,26 @@ +#!/usr/bin/python +from __future__ import division, print_function +from math import pow +import random + +epsilon = 1e-09 + +def derive(function, x): + """Poor man's numerical derivation.""" + return (function(x+epsilon)-function(x-epsilon))/(2*epsilon) + +def newton(function, x_0, max_i=50): + """Find a real root of a function using Newton's method.""" + x = x_0 + for i in range(max_i): + x = x - (function(x)/derive(function, x)) + print('f({}) = {}'.format(x, function(x))) + if abs(function(x)) < epsilon: + return x + break + else: + return x + + +print(newton(lambda x: x**4 + 3*x - 1, x_0=100*random.random())) +#print(newton(lambda x: pow(x, 0.333), x_0=100*random.random()))