Newton Raphson With User Input
Newton Raphson With User Input
def f(x):
return x**3-5*x-9
def g(x):
return 3*x**2-5
def func_input():
function_str = input("Enter your function (use 'x' as the variable) (Example:
x**3 - 5 * x - 9): ")
x = sp.symbols('x')
sp_function = sp.sympify(function_str)
func = sp.lambdify(x, sp_function, modules=['numpy'])
return func, sp_function
def func_derivative(sp_function):
x = sp.symbols('x')
sp_derivative = sp.diff(sp_function, x)
derivative = sp.lambdify(x, sp_derivative, modules=['numpy'])
return derivative, sp_derivative
def nr(func,dx,ig,t,m):
cg=ig
for step in range(1, m + 1):
ng=cg-func(cg)/dx(cg)
if abs(func(ng))<=t:
print(f"the required root is : {ng:.8f}")
return ng
cg=ng
def main():
func, function_str = func_input()
dx, derivative_str = func_derivative(function_str)
ig = float(input("Enter initial guess (x0): "))
t = float(input("Enter tolerable error: "))
m = int(input("Enter maximum steps: "))
nr(func,dx,ig,t,m)
if __name__ == "__main__":
main()