KGreen
KGreen

Reputation: 305

Find the number closest to zero in an array

I have a bunch of numpy arrays that have both positive and negative numbers in them and I want to find the number closest to zero in each array not the smallest number. I also want to retain the signs of the numbers. Example below:

array1 = np.array([5, 3.2, -1.2, -0.2, 7])
array2 = np.array([19, -20, -4.7, 6, 9, 42])
array3 = np.array([4, 0.3, -9, 8, 6, 14])

Ideal output would be something that give me the number closest to zero, so for each array respectively it would be:

"Closest to zero for array 1:" -0.2

"Closest to zero for array 2:" -4.7

"Closest to zero for array 3:" 0.3

Is there any way to do this?

Upvotes: 0

Views: 8483

Answers (5)

Jirukun
Jirukun

Reputation: 11

myList = [4, 1, 88, 44, 3,-1,-7,-19,-0.5,-0.2]

def compute_closest_to_zero(myList):
    positive = []
    negative = []
    if len(myList) == 0:
        print('0')
    else:
        for i in myList:
            if i >= 0:
                positive.append(i)
                #print(positive)
            else:
                negative.append(i)
                #print(negative)
                #print(min(positive))

                
    if min(positive) + max(negative) < 0:
        print(min(positive))
    else:
        print(max(negative))
    return

Blockquote

compute_closest_to_zero(myList)

Upvotes: 1

SnoopyDog
SnoopyDog

Reputation: 33

min1=abs(array1[0])

for i in array1:
    if(abs(i)<abs(min1)):
        min1=i

print("Closest to zero for array 1: "+ str(min1))

Upvotes: 1

season
season

Reputation: 336

if you are trying to get the minimum value

np.minimum([2, 3, 4], [1, 5, 2])

//

np.minimum(np.eye(2), [0.5, 2]) # broadcasting

reference: https://numpy.org/doc/stable/reference/generated/numpy.minimum.html

Upvotes: 0

Chris
Chris

Reputation: 29742

One way without numpy; using min with abs:

for arr in [array1, array2, array3]:
    print(arr, min(arr, key=abs))

Output:

[ 5.   3.2 -1.2 -0.2  7. ] -0.2
[ 19.  -20.   -4.7   6.    9.   42. ] -4.7
[ 4.   0.3 -9.   8.   6.  14. ] 0.3

Upvotes: 4

AKX
AKX

Reputation: 168957

A combination of argmin and abs:

>>> for array in (array1, array2, array3):
...     print(array, array[np.argmin(np.abs(array))])

[ 5.   3.2 -1.2 -0.2  7. ] -0.2
[ 19.  -20.   -4.7   6.    9.   42. ] -4.7
[ 4.   0.3 -9.   8.   6.  14. ] 0.3

Upvotes: 2

Related Questions