2

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?

0

2 Answers 2

7

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
Sign up to request clarification or add additional context in comments.

Comments

2

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.