Suppose I have a function like sqrt(x)
and I am passing a list of numbers through it [-1,0,1]
.
This is going to give me an error saying that a negative argument is passed inside the square root function and the program is going to be halted after that without even checking for the 0 and 1 for which I would have gotten the real and "allowed" results in the first place.
Is there a way I can command python to ignore the values for which it would give errors and move on to the next part of the list?
Perhaps an algorithm like:
Start
x = [-1,0,1]
Pass this list through the function sqrt(x)
Ignore the values for which the function is going to the complex regime
Give the results ([-,0,1])
End
?
Thanks.
CodePudding user response:
import numpy as np
x = [-1, 0, 1]
print(np.sqrt(x))
numpys sqrt function is not throwing an error and returning only valid results.
CodePudding user response:
Just do an explicit filter of your data:
import numpy as np
arr = np.array([-1,0,1])
filtered_arr = arr[arr >= 0]
print(np.sqrt(filtered_arr))
CodePudding user response:
@matszwecja's answer assumes you can tell a priori which arguments give complex-valued answers. This is true for your sqrt
example, but not in the general case. To filter after execution, a slight remix would be:
import numpy as np
arguments = [-1, 0, 1]
results = [x ** 0.5 for x in arguments] # stand in for your more general function
# use numpy for the filtering, for convenience
real_valued_args = np.array(arguments)[~np.iscomplex(results)]