I have a function f(x)
as follows:
def f(x):
if x> 3:
k = x
else:
k = 2*x
return k
If I evaluate f at a single number, say f(2)
, it works fine. But if I evaluate f at a list, say x=[2,3]
, it returns an error:
f([2,3])
TypeError: '>' not supported between instances of 'list' and 'int'
If I evaluate f on an array, I get a similar error
f(arange(1,2,1))
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all().
So, apparently, the problem is that the comparison does not work componentwise. However, other functions (without the if loop) work fine when I input an array (or list). So, my question is: other operations work fine componentwise, why does not the if
work componentwise as well? How can I fix this in order to use f
on arrays?
Aucun commentaire:
Enregistrer un commentaire