0% found this document useful (0 votes)
29 views1 page

Newton Raphson With User Input

The document contains a Python script that implements the Newton-Raphson method for finding roots of a user-defined function. It includes functions for inputting the function, calculating its derivative, and iterating to find the root based on user-provided parameters such as initial guess, tolerable error, and maximum steps. The script utilizes the SymPy library for symbolic mathematics and NumPy for numerical computations.

Uploaded by

aashishpatel129
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views1 page

Newton Raphson With User Input

The document contains a Python script that implements the Newton-Raphson method for finding roots of a user-defined function. It includes functions for inputting the function, calculating its derivative, and iterating to find the root based on user-provided parameters such as initial guess, tolerable error, and maximum steps. The script utilizes the SymPy library for symbolic mathematics and NumPy for numerical computations.

Uploaded by

aashishpatel129
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 1

import sympy as sp

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()

You might also like