[Numpy-discussion] Viewing a float64 array with a float32 array

Zachary Pincus zachary.pincus@yale....
Wed Mar 21 10:58:06 CDT 2012

> I'm not sure if you are referring to rounding errors but that's OK with
> me.
> I was thinking something along the lines of changing how numpy looks at
> the data of A's view by modifying say the stride attribute, etc.

Yes, so was I. As you can see in my example with ints below, you could skip every other byte of the int16 array to "look" at an int8 array. This is because the memory layout of an int8 is a proper subset of int16. (Modulo endian-concerns of course...)

But looking at the link I provided, you can see that taking the first 32 bits of an float64 (or the last 32 or any 32) does not yield something that can be interpreted as a float32. So there's no subset relationship, and you can't do the strides-trick.

To be extra clear, look at the memory layout of a float that's expressible without rounding error:


There's obviously no stride trick whereby one will "look" like the other. 


> On Wed, Mar 21, 2012, at 11:19, Zachary Pincus wrote:
>>> Hi,
>>> Is it possible to have a view of a float64 array that is itself float32?
>>> So that:
>>>>>> A = np.arange(5, dtype='d')
>>>>>> A.view(dtype='f')
>>> would return a size 5 float32 array looking at A's data?
>> I think not. The memory layout of a 32-bit IEEE float is not a subset of
>> that of a 64-bit float -- see e.g. the first table in:
>> http://steve.hollasch.net/cgindex/coding/ieeefloat.html
>> This would work for int8/int16 or other int types (so long as the number
>> doesn't exceed the range of the smaller type), but AFAIK not floats.
>> Note how the subset relationship works for the int8/int16 case, but not
>> float32/float64:
>> str(numpy.array(100,dtype=numpy.int8).data)
>> 'd'
>> str(numpy.array(100,dtype=numpy.int16).data)
>> 'd\x00'
>> str(numpy.array(-100,dtype=numpy.int16).data)
>> '\x9c\xff'
>> str(numpy.array(-100,dtype=numpy.int8).data)
>> '\x9c'
>> str(numpy.array(100,dtype=numpy.float32).data)
>> '\x00\x00\xc8B'
>> str(numpy.array(100,dtype=numpy.float64).data)
>> '\x00\x00\x00\x00\x00\x00Y@'
>> Zach
>> _______________________________________________
>> NumPy-Discussion mailing list
>> NumPy-Discussion@scipy.org
>> http://mail.scipy.org/mailman/listinfo/numpy-discussion
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion@scipy.org
> http://mail.scipy.org/mailman/listinfo/numpy-discussion

More information about the NumPy-Discussion mailing list