from sympy import *
from scipy.optimize import *
from numpy import *
import math
x=symbols("x)")
eqn1=20 3*(29.4*(1-(2.71)**(-x/3))-9.8*x)
print(fsolve(eqn1,[0,10]))
This shows a
Type Error: " 'Add' function is not callable" in line 7
CodePudding user response:
From scipy documentation the way you define your equation is like a python function and then use it in fsolve :
from scipy.optimize import *
def eqn1(x):
return [20 3 * (29.4 * (1 - (2.71) ** (-x[0] / 3)) - 9.8 * x[0])]
print(fsolve(eqn1, [10]))
output:
>>>
[2.26874667]
CodePudding user response:
I'm adding this because I think you need better debugging skills, starting with paying actual attention to the full error message. And also pay attention to the function documentation.
Your code, with a couple of added prints:
136:~/mypy$ python3 stack70732461.py
-29.4*x) 108.2 - 88.2/2.71**(x)/3)
<class 'sympy.core.add.Add'>
Traceback (most recent call last):
File "stack70732461.py", line 10, in <module>
print(fsolve(eqn1,[0,10]))
File "/usr/local/lib/python3.8/dist-packages/scipy/optimize/minpack.py", line 160, in fsolve
res = _root_hybr(func, x0, args, jac=fprime, **options)
File "/usr/local/lib/python3.8/dist-packages/scipy/optimize/minpack.py", line 226, in _root_hybr
shape, dtype = _check_func('fsolve', 'func', func, x0, args, n, (n,))
File "/usr/local/lib/python3.8/dist-packages/scipy/optimize/minpack.py", line 24, in _check_func
res = atleast_1d(thefunc(*((x0[:numinputs],) args)))
TypeError: 'Add' object is not callable
eqn1 is a sympy.add.Add object.
You pulled fsolve from scipy (all those '*' imports can be confusing). That function, down a couple layers ends up trying to do:
thefunc(*((x0[:numinputs],) args))
which given your code amounts to:
eqn1([0,10])
and error says that eqn1 is an Add, not a function. Sympy expressions are not functions. scipy functions like fsolve expect Python functions.
func
callable f(x, *args)
A **function** that takes at least one (possibly vector) argument, and returns a value of the same length.
Others have suggested fixes, but the bottom line is you should not be mixing sympy and scipy without understanding both. Either use fsolve with a proper Python function, or use a sympy solver with your equation.
Changing your code to
...
#print(fsolve(eqn1,[0,10]))
from sympy import symbols, Eq, nsolve
print(nsolve(Eq(eqn1,0), 10))
def eqn1(x):
return [20 3 * (29.4 * (1 - (2.71) ** (-x[0] / 3)) - 9.8 * x[0])]
print(fsolve(eqn1, [10]))
produces a
2.26874667256491
[2.26874667]
