问题
This question is a follow-up of previous question pass class method to fsolve.
@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
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)
回答1:
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.
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.
In the scipy case, returned expression of the function definition has one variable, var, to be solved, and can thus work properly.
来源:https://stackoverflow.com/questions/43071089/different-results-when-passing-function-method-to-equation-solver