简体   繁体   中英

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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM