Pregunta

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?

¿Fue útil?

Solución

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)

Otros consejos

import cmath, random

arr = [random.randint(-100, -1) for _ in range(10)]
sqrt_arr = [cmath.sqrt(i) for i in arr]
print(list(zip(arr, sqrt_arr)))

Result:

[(-43, 6.557438524302j), (-80, 8.94427190999916j), (-15, 3.872983346207417j), (-1, 1j), (-60, 7.745966692414834j), (-29, 5.385164807134504j), (-2, 1.4142135623730951j), (-49, 7j), (-25, 5j), (-45, 6.708203932499369j)]

If speed is an issue, you could use numpy:

import numpy as np
a = np.array([-1+0j, -4, -9])   
np.sqrt(a)
# or: 
a**0.5

result:

array([ 0.+1.j,  0.+2.j,  0.+3.j])
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top