Friday, 15 April 2011

string - Python Float Formatting Minimum Characters -



string - Python Float Formatting Minimum Characters -

i reading big ascii file, converting binary, , compressing cut down file size. reproduce original file exactly. however, number formatting issue. believe original file printed minimum number of characters required uniquely identify floating point number.

import struct x = [3.14, 3.1] y = list(struct.unpack('2f', struct.pack('2f', *x))) print str(x) print str(y)

which returns [3.14, 3.1] [3.140000104904175, 3.0999999046325684]

i print y x. how can that? also, don't understand magic taking place under hood str function. can please explain? using python 2.7.

update:

import struct x = [3.14, 3.1] y = list(struct.unpack('2d', struct.pack('2d', *x))) print str(x) print str(y)

the code above returns:

[3.14, 3.1] [3.14, 3.1]

so str function truncates characters, when value close to 64 bit floating point value. similiar behavior when value close 32 bit floating point value.

try this:

for in y: print "%.2f" %

all str() convert object given string

python string numbers format

1 comment:

  1. I can’t imagine focusing long enough to research; much less write this kind of article. You’ve outdone yourself with this material. This is great content.
    list to string python

    ReplyDelete