python - Different results when passing function / method to equation solver -
this question follow-up of previous question pass class method fsolve.
@jim's answer in question difference between function object name , function call clarified confusion , solved problem. however, when tried similar things in sympy:
from sympy.solvers import solve 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) # works fine, function call solve(func(x), x) # works fine, function call
why have different results? (in scipy need pass function name solver while in sympy need pass function call.) because different implementation of 2 libraries? in above example, if substitute function call function name, exception 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) w in [f, symbols]) file "anaconda3\lib\site-packages\sympy\solvers\solvers.py", line 817, in <genexpr> f, symbols = (_sympified_list(w) 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 @ 0x0000018a37da6518>>'' failed, because of exception being raised: syntaxerror: invalid syntax (<string>, line 1)
when solver provided parameter (func(x), x)
, equivalent provide (x ** 2 - 4, x)
, first part of expression containing declared symbol x
.
however when parameter list (func, x)
, variable in function definition, v
, undefined , not match provided second argument, x
. causes exception raised.
in scipy case, returned expression of function definition has 1 variable, var
, solved, , can work properly.
Comments
Post a Comment