-1

When I go to print my matrix, it prints an error that says 'Float' object has no attribute 'sin'.

While coding in Python, I am attempting to print a matrix in symbolic form using sym.matrix but I am defining my matrix numerically. When I go to print my matrix, it prints an error that says 'Float' object has no attribute 'sin'. It appears that for some reason, my sin function is not being read or outputted properly.


import numpy as np
from scipy.integrate import quad
from numpy import sin, cos, pi

N = 5 

L = 1

r_e = 1.4

mu = 916

def Phi_V(x,n,r):
    return (2/L)**(1/2) * sin(n*np.pi*x/L +n*np.pi/2) * 4.7 * (1-np.exp(-x))**2 * (2/L)**(1/2) * sin(r*np.pi*x/L +r*np.pi/2)
def V_Func(n,r,j):
    return quad(Phi_V, -L/2, L/2, args = (n,r))[0] + (j*j+1)/(2*mu*r_e**2)

V = sym.Matrix(N,N, lambda n,r: V_Func(n + 1 ,r + 1,10))

V

I get this error message:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-38-8624393320b4> in <module>()
     16     return quad(Phi_V, -L/2, L/2, args = (n,r))[0] + (j*j+1)/(2*mu*r_e**2)
     17 
---> 18 V = sym.Matrix(N,N, lambda n,r: V_Func(n + 1 ,r + 1,10))
     19 
     20 V

/anaconda3/lib/python3.7/site-packages/sympy/matrices/dense.py in __new__(cls, *args, **kwargs)
    418 class MutableDenseMatrix(DenseMatrix, MatrixBase):
    419     def __new__(cls, *args, **kwargs):
--> 420         return cls._new(*args, **kwargs)
    421 
    422     @classmethod

/anaconda3/lib/python3.7/site-packages/sympy/matrices/dense.py in _new(cls, *args, **kwargs)
    430             rows, cols, flat_list = args
    431         else:
--> 432             rows, cols, flat_list = cls._handle_creation_inputs(*args, **kwargs)
    433             flat_list = list(flat_list) # create a shallow copy
    434         self = object.__new__(cls)

/anaconda3/lib/python3.7/site-packages/sympy/matrices/matrices.py in _handle_creation_inputs(cls, *args, **kwargs)
   2111                     flat_list.extend(
   2112                         [cls._sympify(op(cls._sympify(i), cls._sympify(j)))
-> 2113                          for j in range(cols)])
   2114 
   2115             # Matrix(2, 2, [1, 2, 3, 4])

/anaconda3/lib/python3.7/site-packages/sympy/matrices/matrices.py in <listcomp>(.0)
   2111                     flat_list.extend(
   2112                         [cls._sympify(op(cls._sympify(i), cls._sympify(j)))
-> 2113                          for j in range(cols)])
   2114 
   2115             # Matrix(2, 2, [1, 2, 3, 4])

<ipython-input-38-8624393320b4> in <lambda>(n, r)
     16     return quad(Phi_V, -L/2, L/2, args = (n,r))[0] + (j*j+1)/(2*mu*r_e**2)
     17 
---> 18 V = sym.Matrix(N,N, lambda n,r: V_Func(n + 1 ,r + 1,10))
     19 
     20 V

<ipython-input-38-8624393320b4> in V_Func(n, r, j)
     14     return (2/L)**(1/2) * sin(n*np.pi*x/L +n*np.pi/2) * 4.7 * (1-np.exp(-x))**2 * (2/L)**(1/2) * sin(r*np.pi*x/L +r*np.pi/2)
     15 def V_Func(n,r,j):
---> 16     return quad(Phi_V, -L/2, L/2, args = (n,r))[0] + (j*j+1)/(2*mu*r_e**2)
     17 
     18 V = sym.Matrix(N,N, lambda n,r: V_Func(n + 1 ,r + 1,10))

/anaconda3/lib/python3.7/site-packages/scipy/integrate/quadpack.py in quad(func, a, b, args, full_output, epsabs, epsrel, limit, points, weight, wvar, wopts, maxp1, limlst)
    339     if weight is None:
    340         retval = _quad(func, a, b, args, full_output, epsabs, epsrel, limit,
--> 341                        points)
    342     else:
    343         retval = _quad_weight(func, a, b, args, full_output, epsabs, epsrel,

/anaconda3/lib/python3.7/site-packages/scipy/integrate/quadpack.py in _quad(func, a, b, args, full_output, epsabs, epsrel, limit, points)
    446     if points is None:
    447         if infbounds == 0:
--> 448             return _quadpack._qagse(func,a,b,args,full_output,epsabs,epsrel,limit)
    449         else:
    450             return _quadpack._qagie(func,bound,infbounds,args,full_output,epsabs,epsrel,limit)

<ipython-input-38-8624393320b4> in Phi_V(x, n, r)
     12 
     13 def Phi_V(x,n,r):
---> 14     return (2/L)**(1/2) * sin(n*np.pi*x/L +n*np.pi/2) * 4.7 * (1-np.exp(-x))**2 * (2/L)**(1/2) * sin(r*np.pi*x/L +r*np.pi/2)
     15 def V_Func(n,r,j):
     16     return quad(Phi_V, -L/2, L/2, args = (n,r))[0] + (j*j+1)/(2*mu*r_e**2)

AttributeError: 'Float' object has no attribute 'sin'

hpaulj
  • 221,503
  • 14
  • 230
  • 353
Ayanna
  • 1
  • 1
  • 6

3 Answers3

1

You've mixed up your imports a bit by importing the individual functions and also referring to them using np.:

import numpy as np
from numpy import sin, cos, pi
[...]sin(n*np.pi*x/L +n*np.pi/2)[...]

Either:

import numpy as np
[...]np.sin(n*np.pi*X/l + n*np.pi/2[...]

Or:

from numpy import sin, cos, pi
[...]sin(n*pi*X/l + n*pi/2[...]

Also you never import sym so the code you've posted is not the code that's producing that error as the compiler would trip over that first. Can you post the actual code that generated this error, or ideally a minimal example.

Ari Cooper-Davis
  • 3,374
  • 3
  • 26
  • 43
1

Fix Your Imports

Check @Ari Cooper-Davis's answer for these fixes first. Make sure the code you post compiles if your going to include import statements.

Here's one way:

import sympy as sym
import numpy as np
from scipy.integrate import quad

You're not going to need numpy's sin, cos, and pi methods because we'll use the sympy ones.

Whitespace

Make sure you when you have an expression, the whitespace around your operators is even. In other words, you can have 1 + 2 and 1+2 but not 1 +2 or 1+ 2. This is just good practice for readability and helps you catch errors in the long run. This long expression strings get really confusing really fast.

Sympy vs. Numpy

These two libraries don't tend to play nice together. One is symbolic and the other is numeric.

As a way to fix this, replace all your np calls with sym (assuming you use import sympy as sym). Sympy has it's own version of sin and pi which you are interchanging with Numpy's versions.

Like so:

return ((2/L)**(1/2)) * sym.sin(n * sym.pi * (x/L) + n * sym.pi/2) * 4.7 * (1 - sym.exp(-x))**2 * (2/L)**(1/2) * sym.sin(r * sym.pi * x/L + r * sym.pi/2)
Ian Burns
  • 96
  • 5
  • This is a quick pass, you may still be able to use Numpy's method's for some things (seemed like `np.exp` worked for me still), but I think you'll definitely want to use Sympy's `sin` method here. – Ian Burns Oct 31 '19 at 18:37
  • 1
    Can you provide some more details about how the OP should fix their imports? Note that the OP isn't using `import sympy as sym` or even includes any imports from sympy at all. Your answer could address this as well as how to avoid name clashes between numpy and sympy. – Code-Apprentice Oct 31 '19 at 21:16
1

If you make a numpy array from mixed objects, such as numbers, strings or symbols, you get an object dtype array.

np.sin(arr) on such an array is performed by calling [x.sin() for x in arr], i.e. it delegates the task to the sin method of each element. Most objects, including floats, don't have such a method, so this fails. The same applies to other numpy functions such as exp and sqrt. Somethings delegate just fine, such as addition.

The only indication of your using sympy is the sym.Matrix call. I don't understand what you are trying to do with that. What kind of symbolic form are you expecting? sympy isn't going to 'reach' into the scipy/numpy code and convert it to symbols. At best it will try to evaluate the code with by passing symbols to the numpy code, resulting in this error.

Mixing sympy and numpy is tricky, and more often than not wrong.

Why sympy lambdify function cannot identify numpy sum function and multiply function

is another example of trying to use sympy and numpy together. My answer is long and and convoluted, but I left it that way to give a sense of how tricky it is to use the two packages together.

In an isympy session:

In [8]: Matrix                                                                  
Out[8]: sympy.matrices.dense.MutableDenseMatrix

In [9]: Matrix(3,3, lambda n,r: n+r)                                            
Out[9]: 
⎡0  1  2⎤
⎢       ⎥
⎢1  2  3⎥
⎢       ⎥
⎣2  3  4⎦

Matrix makes a sympy object by passing the indices to the function. We see this more clearly with:

In [10]: def foo(n,r): 
    ...:     print(n,r, type(n), type(r)) 
    ...:     return n+r 
    ...:                                                                        

In [11]: Matrix(3,3,foo)                                                        
0 0 <class 'sympy.core.numbers.Zero'> <class 'sympy.core.numbers.Zero'>
0 1 <class 'sympy.core.numbers.Zero'> <class 'sympy.core.numbers.One'>
...
Out[11]: 
⎡0  1  2⎤
⎢       ⎥
⎢1  2  3⎥
⎢       ⎥
⎣2  3  4⎦

If we try to use np.sin in this function:

In [15]: def foo(n,r): 
    ...:     return np.sin(r) 
    ...:                                                                        

In [16]: Matrix(3,3,foo)                                                        
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
AttributeError: 'Zero' object has no attribute 'sin'
...

As I explained above, trying to use nonumeric values as np.sin arguments results in the error in delegation to a sin method.

Your code further complicates things by passing the values through the scipy.quad, which in turn passes the integration variable x plus n and r to Phi_V.


Still in the isympy session,

In [26]: L = 1 
    ...:  
    ...: r_e = 1.4 
    ...:  
    ...: mu = 916                                                               

Using the function that @Ian suggests, using the sympy versions of sin, etc:

In [27]: def foo(n,r): 
    ...:     return ((2/L)**(1/2)) * sin(n * pi * (x/L) + n * pi/2) * 4.7 * (1 -
    ...:  exp(-x))**2 * (2/L)**(1/2) * sin(r * pi * x/L + r * pi/2) 
    ...:                                                                        

In [28]: foo(1,2)                                                               
Out[28]: 
              2                    
     ⎛     -x⎞                     
-9.4⋅⎝1 - ℯ  ⎠ ⋅sin(2⋅π⋅x)⋅cos(π⋅x)

In [29]: Matrix(3,3,foo)                                                        
Out[29]: 
⎡0                   0                                    0                 ⎤
⎢                                                                           ⎥
⎢                     2                                2                    ⎥
⎢            ⎛     -x⎞     2                  ⎛     -x⎞                     ⎥
⎢0       9.4⋅⎝1 - ℯ  ⎠ ⋅cos (π⋅x)        -9.4⋅⎝1 - ℯ  ⎠ ⋅sin(2⋅π⋅x)⋅cos(π⋅x)⎥
⎢                                                                           ⎥
⎢                 2                                       2                 ⎥
⎢        ⎛     -x⎞                               ⎛     -x⎞     2            ⎥
⎣0  -9.4⋅⎝1 - ℯ  ⎠ ⋅sin(2⋅π⋅x)⋅cos(π⋅x)      9.4⋅⎝1 - ℯ  ⎠ ⋅sin (2⋅π⋅x)     ⎦

But this doesn't display anything about the quad integration. Nor can it be used as the objective function in quad.

hpaulj
  • 221,503
  • 14
  • 230
  • 353