[Numpy-discussion] max value of np scalars

Robert Kern robert.kern at gmail.com
Tue Sep 29 17:10:22 EDT 2009


On Tue, Sep 29, 2009 at 15:52, Neal Becker <ndbecker2 at gmail.com> wrote:
> I need the max value of an np scalar type.  I had used this code:
>
> def get_max(is_signed, base_type, total_bits):
>    print 'get_max:', is_signed, base_type, total_bits
>    if is_signed:
>        return (~(base_type(-1) << (total_bits-1)))
>    else:
>        print type(base_type (-1) << total_bits)
>        return (~(base_type (-1) << total_bits))
>
> This doesn't work for e.g., np.uint64.  As the 'print' shows,
>  get_max: False <type 'numpy.uint64'> 10
> <type 'long'>
>
> The type of np.uint64 (-1) << 10 is not np.uint64, but long.  This seems
> very strange to me.
>
> So, 2 questions.
>
> 1) Is this expected behavior?

Could be. I'm not entirely sure why it would be doing this, but the
code does fall back to generic object implementations under certain
conditions.

Of course, np.uint64(-1) is the correct answer for unsigned integer
types since we implement wraparound.

> 2) How can I correctly implement get_max?

np.iinfo() for integer types and np.finfo() for floating point types.

In [1]: np.iinfo(np.uint64).max
Out[1]: 18446744073709551615L

In [2]: np.finfo(np.float32).max
Out[2]: 3.4028235e+38

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless
enigma that is made terrible by our own mad attempt to interpret it as
though it had an underlying truth."
  -- Umberto Eco



More information about the NumPy-Discussion mailing list