4

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?

4
  • iterate through the array to find the square root for each? Just like you would do for a non-negative array? Sorry if I misunderstood your question. Commented Jan 21, 2014 at 16:06
  • 1
    By array do you mean list? Commented Jan 21, 2014 at 16:06
  • 7
    map(cmath.sqrt, your_array)? Commented Jan 21, 2014 at 16:07
  • @DSM by array, i mean a list containing say 100 numbers Commented Jan 21, 2014 at 16:52

3 Answers 3

7

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)

Sign up to request clarification or add additional context in comments.

2 Comments

Or this can be written as a list comprehension: [cmath.sqrt(x) for x in lst]
Also note that on python 3.x map returns a map object, so to turn it back into a list you would need list(map(cmath.sqrt, lst))
4
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)]

Comments

3

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])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.