0

When using the numpy module on python I'm used to define functions and then apply them on arrays. For example

import numpy as np

def function(x):
   return x+1

sample = function(np.random.uniform(0, 1, size=100))

print(sample)

The thing is that if the defined function uses a while loop on its definition it will no longer be able to be applied on an array. For example

import numpy as np
 
def truncation(x):
i=0
while x > i/3:
    i += 1
else:
    y = i/3
return y 

sample = truncation(np.random.uniform(0, 1, size=100))

print(sample)

would get the error: "The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()".

I'm very noob, so any sort of help would be really appreciated.

Esteban G.
  • 109
  • 2
  • 1
    Does this answer your question? [ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()](https://stackoverflow.com/questions/10062954/valueerror-the-truth-value-of-an-array-with-more-than-one-element-is-ambiguous) – BhusalC_Bipin Jun 17 '22 at 02:41
  • if `x` is an array, what do you expect `x > i/3` to look like? Remember it must be (True or False) to be following `while`. – Quang Hoang Jun 17 '22 at 02:47
  • I expected x>i/3 to be evaluated in every entry of the array so that the truncation function of an array gives an array with the results of the truncation function for every entry. Is there any other way of writing this? – Esteban G. Jun 17 '22 at 02:52
  • `x>i/3` does evaluate for each element of `x`, but `while` expects a simple True or False, not an array of them. `while` is a basic Python expression, and knows nothing about arrays. How would you do this if `x` was a list? – hpaulj Jun 17 '22 at 04:11
  • With `numpy`'s array operations you might find that there is very often no need to use loops. In your example you could make use of in-built `np.where()` to ditch the `while` with something like: `y = np.where(x <= np.arange(x.shape[0]) / 3)[0][0]`. – L_W Jun 17 '22 at 08:37

0 Answers0