Skip to content

Commit c5adee6

Browse files
committed
added newtonmethod file
1 parent 146a4ae commit c5adee6

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

extra/newtonmethod.py

+45
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
from sympy import *
2+
from sympy.abc import x,y
3+
import matplotlib.pyplot as plt
4+
import math
5+
from tabulate import tabulate
6+
7+
def newtons_method(func, dfunc, x):
8+
9+
def f(x):
10+
f = eval(func)
11+
return f
12+
13+
def df(x):
14+
df = eval(dfunc)
15+
return df
16+
17+
plt.xlabel("value of x")
18+
plt.ylabel("value of y")
19+
plt.title("Shift of x")
20+
vals = []
21+
while round(f(x), 3) != 0:
22+
vals.append([x, f(x)])
23+
i = x - (f(x)/df(x))
24+
x = i
25+
26+
vals = add_dist(vals, (x, f(x)))
27+
print(tabulate(vals, numalign="center", tablefmt="orgtbl", headers=["X Values", "Y Values", f"Dist from {(round(x, 2), 0)}"]))
28+
plt.plot([i[0] for i in vals], [i[1] for i in vals], marker="o")
29+
plt.show()
30+
31+
def add_dist(cords, x):
32+
for cord in cords:
33+
dist = math.dist(cord, x)
34+
cord.append(dist)
35+
36+
return cords
37+
38+
39+
def main():
40+
func = input("Use proper syntax (2x = x*2) \nEnter function: ")
41+
dfunc = str(diff(func, x))
42+
s = float(input("Enter starting point: "))
43+
newtons_method(func, dfunc, s)
44+
45+
main()

0 commit comments

Comments
 (0)