Jun-16-2018, 01:11 AM
Hi, I would like to know how I can improve my function so that I do not trigger the ValueError exception when I do the following(its an implementation of Newton-Raphson):
import sys import sympy as sy def newt(x, fx, x0, precision, iterations): import numpy as np # Initial Error e = np.inf dfdx = fx.diff(x) xini = x0 j = 1 r = 0 while(j<=iterations): xsig = xini - (float(fx.subs(x, xini)) / float(dfdx.subs(x, xini))) xsig = float(xsig) if ((abs(xsig-xini)/abs(xini)) < precision): r = xsig iterations = j e = (abs(xsig-xini)/xini) return dfdx, r, iterations, e j+=1 xini = float(xsig) print ("The method fails after: %s" %iterations) x = sy.Symbol('x') fx = -26 + 85 * x - 91 * x ** 2 + 44 * x ** 3 - 8 * x ** 4 + x ** 5 dfdx, r, iterations, e = newt(x, fx, 10, 0.0001, 2) #2 iterations to trigger the exception print('f(x)=', fx) print("f'(x)=", dfdx) print('Root ', r, ' calculated after ', iterations, ' iterations') print('Error ', e)Thanks