1

How can I find minimum of array of floats in Python? The min() or array.min() did not work. Here is the code:

import numpy as np

z=np.array([[ -4.26141957e-01],
       [ -2.26582552e-01],
       [ -7.28807682e-03],
       [  2.72843324e-02],
       [ -5.59146620e-02],
       [ -2.06062340e-05],
       [  1.06954166e-09],
       [ -6.34170623e-01],
       [  5.07841198e-02],
       [ -1.89888605e-04]])

z_min=z.min()

which gives z_min = -0.63417062312627426. I am a Matlab user so this is confusing to me...

8
  • 4
    Yo what do you want to happen? That answer looks correct to me Commented May 22, 2013 at 13:31
  • 2
    Yeah... it's the right answer. Maybe you want z[np.abs(z).argmin()] the number with the least magnitude? Commented May 22, 2013 at 13:32
  • 1
    That looks correct. Are you forgetting to look at the negative powers of ten, which reduce the magnitude of the numbers? Commented May 22, 2013 at 13:33
  • 4
    @Makaroni -0.634 < -0.0559 is true, isn't it? Then -0.634 is smaller — that's how min() works. Commented May 22, 2013 at 13:58
  • 1
    -10 < -1 Right? Try it in Matlab, too. You'll get the same result. It's just how negative numbers work. Commented May 22, 2013 at 14:00

2 Answers 2

5

z_min = -0.63417062312627426 looks like the right answer. Be careful about scientific notation.

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

Comments

3

np.min() returns the smallest number, or the "largest" negative number (if there are any). In this case the entry at index 7 is the minimum entry. It is -6.34 * 10^-1 in scientific notation, or -0.634... in long-hand.

Printing all in long-hand

Perhaps this will help:

print "\n".join(["%+0.10f" % e for e in z])

-0.4261419570
-0.2265825520
-0.0072880768
+0.0272843324
-0.0559146620
-0.0000206062
+0.0000000011
-0.6341706230
+0.0507841198
-0.0001898886

To verify your answer

The following will show that only one entry has this minimum value.

z <= z.min()

array([[False],
       [False],
       [False],
       [False],
       [False],
       [False],
       [False],
       [ True],
       [False],
       [False]], dtype=bool)

One more example

The number closest to zero can be found like this:

z[np.abs(z).argmin()]

Which is 1.06954166e-09 = 1.069 * 10^-09 in scientific notation or 0.000000000106... in long-hand.

1 Comment

By the way, I guess you probably didn't need all this. I just figured it may help future readers.

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.