0

I try to convert a sympy expression to solve this expression with scipy.optimize.fsolve. This is a minimalistic example:

import numpy as np
import sympy as sy
import scipy as sc
import scipy.optimize as sc

a=sy.symbols('a')
G=sy.sin(a)
test = sy.lambdify(a,G,"numpy") #also "sympy" will not help
sc.fsolve(test,a)

I will get the following error

AttributeError: 'Symbol' object has no attribute 'sin'
TypeError: loop of ufunc does not support argument 0 of type Symbol which has no callable sin method

I use python (3.8.10), numpy (1.20.2), sympy (1.8) and scipy (1.6.2). Some discussions attribute this to a namespace issue, but that shouldn't be the case here. Can someone explain me what I'm doing wrong?

Katoon
  • 65
  • 1
  • 6
  • 2
    You can't use a symbol in calls to scipy functions. So, you can't use `sc.fsolve(...,a)`. You need a float instead, e.g. `sc.fsolve(test, 1.0)` (the second parameter is called `x0`, the starting value around which `fsolve` will search for a root). – JohanC Sep 21 '21 at 11:09
  • Oh shit you're right! In fact I have another script that uses similar code and runs without problems. I searched for a long time where the difference is and ended up with this minimal example. Thanks to you, I realized that in the other script I redefined the symbol in the scipy call by a float. Sorry for this stupid question, – Katoon Sep 21 '21 at 14:36
  • `lambdify` converts the `sy.sin` to `np.sin`. An array containing a symbol will be object dtype. `numpy` evaluates such a `sin` by calling the `sin` method on each of the elements. Almost no one implements `sin` as a method, hence the attribute error. – hpaulj Sep 21 '21 at 15:59

0 Answers0