I want to write a Python function that accepts either a numpy array or a float and repeatedly divides it by 2 until a condition is met. For a float, the loop should continue while the value is greater than 1e-5, and for an array, it should continue until its maximum value is below 1e-5.
Below is a simple example I tried:
def f(x): #float version
while x>1e-5:
x = x/2
return x
def f(x): #np array version
while max(x)>1e-5:
x = x/2
return x
The problem is that using max(x) fails when x isn’t iterable, and the float-based condition x>1e-5 fails for arrays. I’d like to have one single function capable of handling both cases efficiently. What approach should I take?