Python Forum
ValueError in function
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
ValueError in function
#1
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
Reply
#2
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.
Reply
#3
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.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020