469,592 Members | 1,674 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,592 developers. It's quick & easy.

Array and floating point

Hello,

I'm experiencing a problem where the float being appended to the array
is not the same as the result of the appending.
>>from array import *
x = array('f')
x.append(float("0.1"))
x[0]
0.10000000149011612
>>float("0.1")
0.10000000000000001

I'm expecting x[0] = 0.10000000000000001

Thanks
Jonathan Shan

Aug 17 '07 #1
2 1462
Jonathan Shan wrote:
Hello,

I'm experiencing a problem where the float being appended to the array
is not the same as the result of the appending.
>>>from array import *
x = array('f')
x.append(float("0.1"))
x[0]
0.10000000149011612
>>>float("0.1")
0.10000000000000001

I'm expecting x[0] = 0.10000000000000001
array("f") is an array of C floats while Python's float type is a double in
C terms. That's why you lose some precision. Try array("d") instead:
>>from array import array
x = array("d")
x.append(0.1)
x[0]
0.10000000000000001
Peter
Aug 17 '07 #2
Jonathan Shan wrote:
Hello,

I'm experiencing a problem where the float being appended to the array
is not the same as the result of the appending.
>>>from array import *
x = array('f')
x.append(float("0.1"))
x[0]
0.10000000149011612
>>>float("0.1")
0.10000000000000001

I'm expecting x[0] = 0.10000000000000001
'f' denotes a single-precision floating point number. Python's float objects are
double-precision floating point numbers. Use 'd' instead.

--
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

Aug 17 '07 #3

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

9 posts views Thread by Yaroslav Bulatov | last post: by
5 posts views Thread by Koster | last post: by
11 posts views Thread by gouqizi.lvcha | last post: by
14 posts views Thread by rocketman768 | last post: by
9 posts views Thread by ssubbarayan | last post: by
reply views Thread by suresh191 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.