master
E. Almqvist 3 years ago
parent c2e56926d7
commit 4bfe05e5b8
  1. BIN
      mas/newton-raphsons/__pycache__/main.cpython-310.pyc
  2. BIN
      mas/newton-raphsons/__pycache__/sak.cpython-310.pyc
  3. 34
      mas/newton-raphsons/main.py
  4. 57
      mas/newton-raphsons/sak.py

@ -0,0 +1,34 @@
#!/usr/bin/python
import numpy as np
def nullfunc(x):
return 0
def derive(x: float, func=nullfunc, dx=0.1):
return (func(x+dx) - func(x))/dx
def new_rap(x, func=nullfunc, dx=0.1):
new_x = None
try:
while x != new_x:
y = func(x)
der = derive(x, func, dx)
new_x = x - y/der
if new_x == x:
return new_x
else:
x = new_x
return x
except ZeroDivisionError as error:
print(f"{y=} {der=} {new_x=}")
print(error)
def myfunc(x):
return 2*x - 2*(x**2) * np.sin(x) + 0.1
if __name__ == "__main__":
out = new_rap(3, myfunc, 0.00000001)
print(f"x={out}")
print(f"f(x)={myfunc(out)}")

@ -0,0 +1,57 @@
#!/usr/bin/python
import operator
def new_rap(x, func: str="0", der: str="0", iter=0):
y_exper = func.replace("x", str(x))
der_exper = der.replace("x", str(x))
y = eval(y_exper)
der = eval(der_exper)
print(f"new_x = {x} - {y}/{der} [{iter}]")
new_x = x - (y / der)
return new_x
# def new_rap(x, func=nullfunc, dx=0.1):
# new_x = None
# try:
# while x != new_x:
# y = func(x)
# der = derive(x, func, dx)
# new_x = x - y/der
# if new_x == x:
# return new_x
# else:
# x = new_x
# return x
# except ZeroDivisionError as error:
# print(f"{y=} {der=} {new_x=}")
# print(error)
def eval_func( func: str, x: float ):
y_exper = func.replace("x", str(x))
return eval(y_exper)
def new_rap_method(x, funcstr: str="0", derstr: str="0", per=10):
new_x = None
i = 0
while True:
y = eval_func(funcstr, x)
der = eval_func(derstr, x)
print(f"new_x = {x} - {y}/{der} [{i}]")
new_x = x - (y / der)
i += 1
if round(eval_func(funcstr, new_x), per) == 0:
return round(new_x, per)
else:
x = new_x
if __name__ == "__main__":
func = input("f(x) = ")
der = input("f'(x) = ")
randx = float(input("x = "))
print("Doing newton-raphsons method to get root...")
x = new_rap_method(randx, func, der)
print(f"{x=}")
Loading…
Cancel
Save