Home > Net >  Solving only size-1 arrays can be converted to Python scalars error
Solving only size-1 arrays can be converted to Python scalars error

Time:10-29

I have the following function however I have the error only "size-1 arrays can be converted to Python scalars" when I run the program

import math as math
import numpy as np

def chebs(c, d, n):
    k = np.array(range(n))
    y = ((2*k  1)*np.pi)/(4*(n 1))
    return c*math.sin(y)**2   d*math.cos(y)**2

is there a way to circumvent the error? I'm assuming it comes from my use of math in the function?

CodePudding user response:

You can't mix numpy. with math. functions, just use numpy. functions only:

import numpy as np

def chebs(c, d, n):
    k = np.arange(n)
    y = ((2 * k   1) * np.pi) / (4 * (n   1))
    return c * np.sin(y) ** 2   d * np.cos(y) ** 2

CodePudding user response:

The functions in math are usually expecting a single number as argument; whereas the functions in numpy are usually expecting anything from a single number to a multidimensional array, and will apply the mathematical function to every element in the array.

For instance:

>>> import math
>>> import numpy as np

>>> math.sqrt(4)
2.0
>>> math.sqrt(25)
5.0
>>> np.sqrt(4)
2.0
>>> np.sqrt(25)
5.0

>>> np.sqrt([4,25])
array([2., 5.])

>>> math.sqrt([4,25])
TypeError: must be real number, not list

>>> math.sqrt(np.array([4,25]))
TypeError: only size-1 arrays can be converted to Python scalars

As it turns out, numpy arrays that contain a single number are able to implicitly convert themselves to a single number without array, when needed, so this works:

>>> math.sqrt(np.array([[25]]))
5.0

The error message you got was telling you "the array y contains more than one number, so it can't be converted to a single number, so you can't call math.sin on it."

If you want to apply a function from math to every element in a list, you can do it using a list comprehension or using builtin function map. However, note that the whole point of numpy is to perform computations very fast on large arrays, and using list comprehensions or map will defeat that purpose.

>>> list(map(math.sqrt, [4, 25]))
[2.0, 5.0]
>>> [math.sqrt(x) for x in [4,25]]
[2.0, 5.0]
  • Related