[Numpy-discussion] upcast

Charles R Harris charlesr.harris at gmail.com
Wed Aug 30 18:12:14 CDT 2006

On 8/30/06, Lars Friedrich <lfriedri at imtek.de> wrote:
> Hello,
> I would like to discuss the following code:
> #***start***
> import numpy as N
> a = N.array((200), dtype = N.uint8)
> print (a * 100) / 100

This is actually a scalar, i.e., a zero dimensional array. N.uint8(200)
would give you the same thing, because (200) is a number, not a tuple like
(200,). In any case

In [44]:a = array([200], dtype=uint8)
In [45]:a*100
Out[45]:array([32], dtype=uint8)
In [46]:uint8(100)*100

i.e. , the array arithmetic is carried out in mod 256 because Numpy keeps
the array type when multiplying by scalars. On the other hand, when
multiplying a *scalar* by a number, the lower precision scalars are
upconverted in the conventional way. Numpy makes the choices it does for
space efficiency. If you want to work in uint8 you don't have to recast
every time you multiply by a small integer. I suppose one could demand using
uint8(1) instead of 1, but the latter is more convenient.

Integers can be tricky once the ordinary precision is exceeded and modular
arithmetic takes over, it just happens more easily for uint8 than for

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://projects.scipy.org/pipermail/numpy-discussion/attachments/20060830/4ff0bffd/attachment-0001.html 

More information about the Numpy-discussion mailing list