I want to pass a numpy array arr
to what_a_function
and print the resulting array, and this should be done without using loop. I know it is ugly and unfriendly, but I have to do so. I tried with vectorize
but kept failing. May anyone share some pointers please? Thanks!
import numpy as np
def what_a_function(x):
return -np.cos(x.all()) * (0.5 < np.sin(x) < 2) + (np.sin(x) <= 0.5) + (x ** 2) * (np.sin(x) >= 2)
a=1
b=5
vfunc = np.vectorize(what_a_function)
arr = np.arange(a,b+0.1,0.1)
print(arr)
print(vfunc(arr))
And it will complain AttributeError: 'float' object has no attribute 'all'
.
That ' super ugly and unfriendly' equation doesn't make sense. What kind of x
value is it supposed to evaluate?
-np.cos(x.all()) * (0.5 < np.sin(x) < 2) + (np.sin(x) <= 0.5) + (x ** 2) * (np.sin(x) >= 2)
x.all()
requires an array (with all
method), and returns a boolean (scalar or array), which is a nonsense input for np.cos
.
np.sin(x)
is ok with a scalar or array, but the 0.5<...<2
only works for a scalar (it's Python that doesn't work for numpy).
The next np.sin(x)<=.5
will produces a boolean (scalar or array). x**2
will be a numeric value.
The +
and *
will sort of work, converting the boolean True/False to 1/0 integers. But logical operators are better.
If we knew what is was supposed to do, we could probably write it to work directly with a numeric array. np.vectorize
is not a good substitute for writing proper array compatible code. As I commented, vectorize
passes the array values to the function one by one, as scalars. That's why the all
method produces an error (and doesn't make sense). On top of that vectorize
is slow.
A straight forward list comprehension is faster:
np.array([your_function(i) for i in x])
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments