diegoaguilar
diegoaguilar

Reputation: 8376

Evaluation of symbolic Differentiation with Sympy in Python

I'm coding NewtonRaphson algorithm in python using Sympy library, this is my algorithm implementation:

def NewtonRaphson(fx,p0,tolerancia,iteracionesMaximas):
    print
    fx = S(fx)
    x = Symbol('x')
    i = 1
    p = 0.0

    while i<= iteracionesMaximas:
        
        y = fx.subs(x,p0)
        yy = diff(fx,x).subs(x,p0)
        p = p0 - (y/yy)

        if absolute(p-p0) < tolerancia:
            print "Se encontró la raíz y={raiz} luego de {n} iteraciones".format(raiz=p, n=i-1)
            return

        i += 1
        print "{i}\t{p}\t{p0}".format(i=i-1,p=p,p0=p0)
        p = p0

    print "El método falló luego de {i} iteraciones".format(i=i-1)

I'm obtaining a raise with the following message:

line 18, in NewtonRaphson    
    yy = diff(fx,x).subs(x,p0)    
  File "/usr/local/lib/python2.7/dist-packages/numpy/lib/function_base.py", line 984, in diff    
    if n < 0:    
  File "/usr/local/lib/python2.7/dist-packages/sympy/core/relational.py", line 226, in __nonzero__    
    raise TypeError("symbolic boolean expression has no truth value.")    
TypeError: symbolic boolean expression has no truth value.    

I call function being fx a string equal to 'x**3-x-1'and input the call NewtonRaphson(fx,1.7,10**(-4),17).

What have I got wrong?

Upvotes: 1

Views: 800

Answers (1)

IanH
IanH

Reputation: 10690

It looks like you are passing a symbolic expression to numpy's absolute function. Judging by your code I'd bet that your import statements were

from pylab import *
from sympy import *

If that was the case, you should just replace absolute with Abs so that you are using the absolute value function built in to sympy instead of the one meant for numpy arrays.

Also, you will need to replace p = p0 with p0 = p for the algorithm to run properly.

Here is a working version with the import statements changed somewhat. I have also removed some of the unnecessary statements.

import sympy as sy

x = sy.symbols('x')
fx = x**3 - x - 1

def NewtonRaphson(fx,p0,tolerancia,iteracionesMaximas):

    for i in xrange(iteracionesMaximas):

        y = fx.subs(x, p0)
        yy = sy.diff(fx,x).subs(x, p0)
        p = p0 - (y / yy)

        if sy.Abs(p-p0) < tolerancia:
            print "Se encontró la raíz y={raiz} luego de {n} iteraciones".format(raiz=p, n=i-1)
            return

        print "{i}\t{p}\t{p0}".format(i=i+1,p=p,p0=p0)
        p0 = p

    print "El método falló luego de {i} iteraciones".format(i=i-1)

NewtonRaphson(fx,1.7,10**(-4),17)

Upvotes: 1

Related Questions