how do you convert and array of doubles into floats?

Tim Peters tim.peters at gmail.com
Fri Sep 15 15:25:15 EDT 2006


[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



More information about the Python-list mailing list