简体   繁体   English

在 Python 中使用 Sympy 评估符号微分

[英]Evaluation of symbolic Differentiation with Sympy in Python

I'm coding NewtonRaphson algorithm in python using Sympy library, this is my algorithm implementation:我正在使用 Sympy 库在 python 中编写 NewtonRaphson 算法,这是我的算法实现:

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) .我调用函数是fx一个等于'x**3-x-1'的字符串并输入调用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.看起来您正在将符号表达式传递给 numpy 的绝对函数。 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.如果是这种情况,您应该只用Abs替换absolute以便您使用 sympy 内置的绝对值函数,而不是用于 numpy 数组的绝对值函数。

Also, you will need to replace p = p0 with p0 = p for the algorithm to run properly.此外,您需要将p = p0替换为p0 = p以使算法正常运行。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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