Reputation: 141
using 'struct pack and unpack' on floating point number 0.01 outputs 0.009999999776482582. For my project I would have to configure values which are float and the same needs to be stored in binary file and I would need this data to analyze later and I need the exact values that was configured.
Can some one help me if there is any way that I could store the exact value 0.01 and retrieve the same.
Based on some of the post I have already tried using double instead of float and it works but the problem with using double is my file size increases. I have a lot of parameters which is float and can take values any where between 0 to 5. Hence any other suggestion would be appreciated.
Here is the sample code
import struct
a = 0.01
b = struct.pack('<f', a)
c = struct.unpack('<f', b)
print c
(0.009999999776482582,)
Upvotes: 3
Views: 3402
Reputation: 32923
You say that numbers go from 0 to 5. If you only need two decimal places (0.00, 0.01, ..., 5.00) then you can store the numbers as 16 bit integers, first by multiplying the number by 100, and then when reading dividing the number by 100:
>>> import struct
>>> digits = 2
>>> a = 0.01
>>> b = struct.pack('<H', int(round(a, digits)) * (10 ** digits))
>>> c = struct.unpack('<H', b)
>>> print (c[0] / (10.0 ** digits))
0.01
Storing numbers with H format you can actually save 50% space compared to floats. If you need more precision, more than two decimal places, you need yo multiply the number and then dividing by 1000, 10000, etc, changing the format from H to I.
Upvotes: 2
Reputation: 49866
There is no floating point number 0.01
. IEEE floating point numbers do not represent the entire real number line; they represent an approximation using a particular binary scheme. The closest approximation has the decimal representation 0.009999999776482582.
You could try serializing a textual representation (e.g. json) or pickle a BigDecimal which can represent arbitrary precisions.
Upvotes: 2