I know that Python has the cmath module to find the square root of negative numbers.
What I would like to know is, how to do the same for an array of say 100 negative numbers?
You want to iterate over elements of a list and apply the sqrt
function on it so. You can use the built-in function map
which will apply the first argument to every elements of the second:
lst = [-1, 3, -8]
results = map(cmath.sqrt, lst)
Another way is with the classic list comprehension:
lst = [-1, 3, -8]
results = [cmath.sqrt(x) for x in lst]
Execution example:
>>> lst = [-4, 3, -8, -9]
>>> map(cmath.sqrt, lst)
[2j, (1.7320508075688772+0j), 2.8284271247461903j, 3j]
>>> [cmath.sqrt(x) for x in lst]
[2j, (1.7320508075688772+0j), 2.8284271247461903j, 3j]
If you're using Python 3, you may have to apply list()
on the result of map (or you'll have a ietrator object)