![]() |
ValueError in function - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: Homework (https://python-forum.io/forum-9.html) +--- Thread: ValueError in function (/thread-10977.html) |
ValueError in function - Tipillo - Jun-16-2018 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 RE: ValueError in function - Larz60+ - Jun-16-2018 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. RE: ValueError in function - ichabod801 - Jun-16-2018 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. |