Search code examples
pythonarraysnumpyminimum

minimum of array of floats in python


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...


Solution

  • 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.