将函数/方法传递给方程求解器时的不同结果 [英] Different results when passing function / method to equation solver
问题描述
这个问题是上一个问题的后续将类方法传递给 fsolve.
This question is a follow-up of previous question pass class method to fsolve.
@jim 在关于函数对象名称和函数调用之间差异的问题中的回答澄清了我的困惑并解决了问题.但是,当我在 sympy 中尝试类似的事情时:
@jim's answer in that question about difference between the function object name and a function call clarified my confusion and solved the problem. However, when I tried similar things in sympy:
from sympy.solvers import solve
from sympy import Symbol
class Demo():
def __init__(self, var):
self.i = var
def func(self):
return self.i ** 2 - 4
x = Symbol('x')
def func(v):
return v ** 2 - 4
new = Demo(x)
solve(new.func(), x) # This works fine, even as a function call
solve(func(x), x) # This works fine, even as a function call
为什么我有不同的结果?(在 scipy 中我需要将函数名称传递给求解器,而在 sympy 中我需要传递函数调用.)是因为两个库的实现不同吗?在上面的例子中,如果我用函数名替换函数调用,则会引发异常:
Why do I have different results? (In scipy I need to pass function name to solver while in sympy I need to pass the function call.) Is it because different implementation of the two libraries? In the above example, if I substitute the function call with function name, exception will be raised:
File "<ipython-input-26-3554c1f86646>", line 13, in <module>
solve(new.func, x)
File "Anaconda3\lib\site-packages\sympy\solvers\solvers.py", line 817, in solve
f, symbols = (_sympified_list(w) for w in [f, symbols])
File "Anaconda3\lib\site-packages\sympy\solvers\solvers.py", line 817, in <genexpr>
f, symbols = (_sympified_list(w) for w in [f, symbols])
File "Anaconda3\lib\site-packages\sympy\solvers\solvers.py", line 808, in _sympified_list
return list(map(sympify, w if iterable(w) else [w]))
File "Anaconda3\lib\site-packages\sympy\core\sympify.py", line 324, in sympify
raise SympifyError('could not parse %r' % a, exc)
SympifyError: Sympify of expression 'could not parse '<bound method Demo.func of <__main__.Demo object at 0x0000018A37DA6518>>'' failed, because of exception being raised:
SyntaxError: invalid syntax (<string>, line 1)
推荐答案
当求解器提供参数(func(x), x)
时,相当于提供(x ** 2 - 4, x)
,其中第一部分是包含声明符号x
的表达式.
When the solver is provided parameter (func(x), x)
, it is equivalent to provide (x ** 2 - 4, x)
, the first part of which is an expression containing the declared symbol x
.
然而,当参数列表是 (func, x)
时,函数定义中的变量 v
未定义并且与作为第二个参数提供的不匹配,这是 x
.这会导致引发异常.
However when the parameter list is (func, x)
, the variable in function definition, v
, is undefined and does not match that provided as the second argument, which is x
. This causes exception to be raised.
在 scipy 情况下,函数定义的返回表达式有一个变量 var
需要求解,因此可以正常工作.
In the scipy case, returned expression of the function definition has one variable, var
, to be solved, and can thus work properly.
这篇关于将函数/方法传递给方程求解器时的不同结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!