-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnewton.py
executable file
·39 lines (33 loc) · 945 Bytes
/
newton.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#!/usr/bin/env python
import math
import sys
# Finding roots of f(x) using Newton's method
f = lambda x :float(x*x + 2*x + 1) # f(x) = 0
f_ = lambda x : float(2*x + 2)
def newton(p, n):
print('Po = ',p)
for _ in range(n):
try:
y=f(p)
y_=f_(p) #f'(x)
except:
print("The values must be in range")
sys.exit(1)
if y == 0:
print(p)
sys.exit(1)
try:
p=p-y/y_
except:
print("Derivative of y became zero at some point during calculations, consider using secant or false position technique")
sys.exit(1)
print(f'P{_+1} = {p}')
print(p)
if __name__ == "__main__":
if len(sys.argv) < 2:
p = float(input('Enter Po: '))
n = int(input('number of iterations: '))
else:
p = float(sys.argv[1])
n = int(sys.argv[2])
newton(p, n)