1

I am to use the Math Library to do some calculations on an array.
I tried something like this:

import numpy as np
import math
a = np.array([0, 1, 2, 3])
a1 = np.vectorize(a)
print("sin(a) = \n", math.sin(a1)) 

Unfortunately it does not work. An error occur: "TypeError: must be real number, not vectorize".

How can I use the vectorize function to be able to calculate that kind of things?

6
  • 1
    I'm not sure what you're trying to do. As far as I can tell, vectorize expects you to pass a function, but you passed an array. And math.sin of course expects you to pass a number, but you've passed a vectorized (essentially a function). What are you actually trying to accomplish? Commented Oct 5, 2017 at 19:06
  • 2
    Read the docs of numpy again, carefully! You probably just want np.sin(a) (no need to import math; no need to mix these, and especially no need to use vectorize). Commented Oct 5, 2017 at 19:07
  • 2
    And why do you need to use math? Commented Oct 5, 2017 at 19:09
  • 1
    The canonical way if np.sin is to be avoided is to define f=np.vectorize(math.sin) and apply f(a). Commented Oct 5, 2017 at 19:14
  • 1
    Sounds like a crap assignment Commented Oct 5, 2017 at 20:44

2 Answers 2

7

The whole point of numpy is that you don't need any math method or any list comprehension:

>>> import numpy as np
>>> a = np.array([0, 1, 2, 3])
>>> a + 1
array([1, 2, 3, 4])
>>> np.sin(a)
array([ 0.        ,  0.84147098,  0.90929743,  0.14112001])
>>> a ** 2
array([0, 1, 4, 9])
>>> np.exp(a)
array([  1.        ,   2.71828183,   7.3890561 ,  20.08553692])

You can use a as if it were a scalar and you get the corresponding array.

If you really need to use math.sin (hint: you don't), you can vectorize it (the function itself, not the array):

>>> vsin = np.vectorize(math.sin)
>>> vsin(a)
array([ 0.        ,  0.84147098,  0.90929743,  0.14112001])
Sign up to request clarification or add additional context in comments.

Comments

3
import numpy as np
import math
a = np.array([0, 1, 2, 3])
print("sin(a) = \n", [math.sin(x) for x in a])

math.sin requires one real number at a time.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.