Skip to content

Commit 24bad2e

Browse files
authored
Add files via upload
There are three methods that find approximately the roots of a non-linear function
1 parent 7f87515 commit 24bad2e

File tree

3 files changed

+66
-0
lines changed

3 files changed

+66
-0
lines changed

Bisection.py

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
import math
2+
3+
4+
def bisection(function, a, b): # finds where the function becomes 0 in [a,b] using bolzano
5+
6+
start = a
7+
end = b
8+
if function(a) == 0: # one of the a or b is a root for the function
9+
return a
10+
elif function(b) == 0:
11+
return b
12+
elif function(a) * function(b) > 0: # if noone of these are root and they are both possitive or negative,
13+
# then his algorith can't find the root
14+
print("couldn't find root in [a,b]")
15+
return
16+
else:
17+
mid = (start + end) / 2
18+
while abs(start - mid) > 0.0000001: # untill we achive percise equals to 10^-7
19+
if function(mid) == 0:
20+
return mid
21+
elif function(mid) * function(start) < 0:
22+
end = mid
23+
else:
24+
start = mid
25+
mid = (start + end) / 2
26+
return mid
27+
28+
29+
def f(x):
30+
return math.pow(x, 3) - 2*x -5
31+
32+
33+
print(bisection(f, 1, 1000))

Intersection.py

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import math
2+
3+
def intersection(function,x0,x1): #function is the f we want to find its root and x0 and x1 are two random starting points
4+
x_n = x0
5+
x_n1 = x1
6+
while True:
7+
x_n2 = x_n1-(function(x_n1)/((function(x_n1)-function(x_n))/(x_n1-x_n)))
8+
if abs(x_n2 - x_n1)<0.00001 :
9+
return x_n2
10+
x_n=x_n1
11+
x_n1=x_n2
12+
13+
def f(x):
14+
return math.pow(x,3)-2*x-5
15+
16+
print(intersection(f,3,3.5))

NeutonMethod.py

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import math
2+
3+
def newton(function,function1,startingInt): #function is the f(x) and function1 is the f'(x)
4+
x_n=startingInt
5+
while True:
6+
x_n1=x_n-function(x_n)/function1(x_n)
7+
if abs(x_n-x_n1)<0.00001:
8+
return x_n1
9+
x_n=x_n1
10+
11+
def f(x):
12+
return math.pow(x,3)-2*x-5
13+
14+
def f1(x):
15+
return 3*math.pow(x,2)-2
16+
17+
print(newton(f,f1,3))

0 commit comments

Comments
 (0)