From 24bad2e27359bfd1166504e369c648089651e2a1 Mon Sep 17 00:00:00 2001 From: MindTraper Date: Sun, 17 Dec 2017 22:02:36 +0200 Subject: [PATCH] Add files via upload There are three methods that find approximately the roots of a non-linear function --- Bisection.py | 33 +++++++++++++++++++++++++++++++++ Intersection.py | 16 ++++++++++++++++ NeutonMethod.py | 17 +++++++++++++++++ 3 files changed, 66 insertions(+) create mode 100644 Bisection.py create mode 100644 Intersection.py create mode 100644 NeutonMethod.py diff --git a/Bisection.py b/Bisection.py new file mode 100644 index 000000000..590197cb7 --- /dev/null +++ b/Bisection.py @@ -0,0 +1,33 @@ +import math + + +def bisection(function, a, b): # finds where the function becomes 0 in [a,b] using bolzano + + start = a + end = b + if function(a) == 0: # one of the a or b is a root for the function + return a + elif function(b) == 0: + return b + elif function(a) * function(b) > 0: # if noone of these are root and they are both possitive or negative, + # then his algorith can't find the root + print("couldn't find root in [a,b]") + return + else: + mid = (start + end) / 2 + while abs(start - mid) > 0.0000001: # untill we achive percise equals to 10^-7 + if function(mid) == 0: + return mid + elif function(mid) * function(start) < 0: + end = mid + else: + start = mid + mid = (start + end) / 2 + return mid + + +def f(x): + return math.pow(x, 3) - 2*x -5 + + +print(bisection(f, 1, 1000)) diff --git a/Intersection.py b/Intersection.py new file mode 100644 index 000000000..22c50f2ec --- /dev/null +++ b/Intersection.py @@ -0,0 +1,16 @@ +import math + +def intersection(function,x0,x1): #function is the f we want to find its root and x0 and x1 are two random starting points + x_n = x0 + x_n1 = x1 + while True: + x_n2 = x_n1-(function(x_n1)/((function(x_n1)-function(x_n))/(x_n1-x_n))) + if abs(x_n2 - x_n1)<0.00001 : + return x_n2 + x_n=x_n1 + x_n1=x_n2 + +def f(x): + return math.pow(x,3)-2*x-5 + +print(intersection(f,3,3.5)) diff --git a/NeutonMethod.py b/NeutonMethod.py new file mode 100644 index 000000000..791c256af --- /dev/null +++ b/NeutonMethod.py @@ -0,0 +1,17 @@ +import math + +def newton(function,function1,startingInt): #function is the f(x) and function1 is the f'(x) + x_n=startingInt + while True: + x_n1=x_n-function(x_n)/function1(x_n) + if abs(x_n-x_n1)<0.00001: + return x_n1 + x_n=x_n1 + +def f(x): + return math.pow(x,3)-2*x-5 + +def f1(x): + return 3*math.pow(x,2)-2 + +print(newton(f,f1,3)) \ No newline at end of file