Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Square root of a negative array Python

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?

like image 979
Srivatsan Avatar asked Dec 11 '22 08:12

Srivatsan


2 Answers

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)

like image 75
Maxime Lorant Avatar answered Dec 29 '22 11:12

Maxime Lorant


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)]
like image 20
senshin Avatar answered Dec 29 '22 11:12

senshin