-
Notifications
You must be signed in to change notification settings - Fork 0
/
newton_raphson.py
42 lines (35 loc) · 1.17 KB
/
newton_raphson.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
39
40
41
42
# -*- coding: utf-8 -*-
"""newton_raphson.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1YMrPIbLwmFUr2LLROIMEZfpfu5af3F6t
"""
def evaluate_polynomial(coefficients, x):
result = 0
power = len(coefficients) - 1
for coeff in coefficients:
result += coeff * (x ** power)
power -= 1
return result
def newton_raphson(x,array,coeff):
h = evaluate_polynomial(array, x) / evaluate_polynomial(coeff, x)
while abs(h) >= 0.0001:
h = evaluate_polynomial(array, x) / evaluate_polynomial(coeff, x)
# x(i+1) = x(i) - f(x) / f'(x)
x = x - h
print("The value of the root is : ",
"%.4f"% x)
d = int(input("Enter the highest degree of the polynomial: "))
array = []
for i in range(d + 1):
f = d - i
c = int(input("Enter the coefficient of x ^"+str(f)+" : "))
array.append(int(c))
print("Enter the coefficients of derivative : ")
coeff = []
for i in range(d):
f = d - i - 1
c = int(input("Enter the coefficient of x ^"+str(f)+" : "))
coeff.append(c)
i = int(input("Enter the initial guess: "))
newton_raphson(i,array,coeff)