-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNewton-Raphson_Method.py
More file actions
38 lines (28 loc) · 854 Bytes
/
Newton-Raphson_Method.py
File metadata and controls
38 lines (28 loc) · 854 Bytes
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
import sympy
import math
# import pylab
# import numpy
def new_raph(expression, x0, tol):
x = sympy.Symbol('x')
f = sympy.sympify(expression)
df = sympy.diff(f, x)
xn = x0
fval = f.subs(x, xn)
dfval = df.subs(x, xn)
while (abs(fval/dfval) >= tol):
fval = f.subs(x, xn)
dfval = df.subs(x, xn)
if abs(fval/dfval) < tol:
return xn
xn = xn - fval/dfval
return None
expression = input("Enter the mathematical expression carefully : ")
tolerence = float(
input('Enter the tolerence or maximum error in the solution : '))
x0 = float(input('Enter the initial guess : '))
output = new_raph(expression, x0, tolerence)
if output is not None:
print('\nNewton-Raphson Method works :) ')
print(f'Output is : {output}')
else:
print('Newton-Raphson Method fails :( ')