Python Forum

Full Version: ValueError in function
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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
Please be more specific. Where exactly is the ValueError being issued, any example?
Once identified, you can use a try, except block to take proper action when a value error is encountered.
Your function does not return anything, so you get a value error when you try to assign it to a tuple. You need a return statement with the four things you're trying to get out of it on line 28.