[python] struct module round off error?

D

David Stockwell

Hi,

When I started playing with the struct module, I wrote a simple little test
program. I got the syntax bugs out of the way and found something that
seems a bit odd.

Here is my code
----- START ----
import struct
print "Test of struct module"
a = 5
b = 9
c = 'text'
d = 50.3
myformat = 'ii4sf'
print 'Original value for d[%s]' % d
mystruct = struct.pack(myformat,a,b,c,d)
print "packed mystruct.", mystruct, "., #bytes:", len(mystruct)
unstruct = struct.unpack(myformat,mystruct)
print 'After unpacking: ', unstruct
----- FIN de code -----
Here is the output
----- Start output ------
Test of struct module
Original value for d[50.3]
packed mystruct. text33IB ., #bytes: 16
After unpacking: (5, 9, 'text', 50.299999237060547)
----- FIN de output ---

My question is with the 'd' object that I've setup.

When I first set it and print it, it has the correct value (50.3).

However all i did was pack it, and then unpack it and it lost its definite
value of 50.3.
After the unpack it was approximately 50.3 (50.29999......)

I tried changing the format of d in the pack to a double but still got the
same answer of approximately 50.3. The only difference I see here is the
double is an 64 bit number and the float a 32 bit number.

What can I do short of data manipulation to force the correct number?

One way to do this would be to normalize the number to something like this

d = 50.3 * 10
then do the pack like this
pack('d',d)
later when i unpack it ( Interesting side note: 503.0 packed as a 'd', when
unpacked comes out 503.0 as opposed to 503)
then div by 10.

does python implement the IEEE fp standard, or does it implement java's
approach (which uses less bits)?

What can I do to prevent this sort of round off error so I can guarantee my
numbers stay correct when I use python structs?



David
-------
free phone: http://cellphone.duneram.com/index.html
Cam: http://www.duneram.com/cam/index.html
Tax: http://www.duneram.com/index.html

_________________________________________________________________
Is your PC infected? Get a FREE online computer virus scan from McAfee®
Security. http://clinic.mcafee.com/clinic/ibuy/campaign.asp?cid=3963
 
P

Peter Hansen

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top