how do you convert and array of doubles into floats?

SpreadTooThin bjobrien62 at gmail.com
Fri Sep 15 16:28:55 EDT 2006


Tim Peters wrote:
> [Marc 'BlackJack' Rintsch]
> >> What about:
> >>
> >> b = array.array('f', a)
>
> [Diez B. Roggisch]
> > AFAIK d and f are synonym for arrays, as python doesn't distinguish
> > between these two on a type-level. And double it is in the end.
>
> While Python has no type of its own corresponding to the native C
> `float`, the `array` and `struct` modules do understand the native C
> `float` .  A Python float (same as a C `double`) gets converted to a C
> `float` when stored into one of those, and a C `float` is converted to
> a Python float (C `double`) when a value is extracted.
>
> >>> from array import array
> >>> x = 1.0000000001
> >>> x
> 1.0000000001
> >>> array('d', [x])[0]   # full precision is preserved
> 1.0000000001
> >>> array('d', [x])[0] == x
> True
> >>> array('f', [x])[0]   # trailing bits are lost
> 1.0
> >>> array('f', [x])[0] == x
> False

The point being that when I say
b.tofile(f)  I expect the write to write 32 bit floats.




More information about the Python-list mailing list