Dan Rowles d.rowles at
Mon Feb 25 16:51:54 GMT 2008


I have encountered some weirdness with floating point numbers, and I was 
hoping for your collective wisdom on what to do next.

I have two values that are being generated by some test code, and are 
being compared with the "is" method in Test::More. One is calculated 
from a database, the other is calculated via Statistics::Descriptive, in 
order to confirm that an SQL query is working properly.

My code says:-
is(sprintf('%.5f', $this), sprintf('%.5f', $that));

The test fails, stating:-
#   Failed test 'max score is ok'
#   in t/reports/13health_change_per_procedure.t at line 241.
#          got: '4.74812'
#     expected: '4.74811'

Fair enough - they are different. Printing out their values shows:-
# THIS: '4.748115'
# THAT: '4.748115'

The numbers are identical when printed, but are rounded differently. So 
I used the "Dump" method in Devel::Peek to have a closer look at these 

THIS: SV = PVNV(0xa2ac528) at 0xa1c3a6c
   REFCNT = 1
   IV = 0
   NV = 4.748115
   PV = 0xa2b36e8 "4.748115"\0
   CUR = 8
   LEN = 20

THAT: SV = PVNV(0xa2ac4f8) at 0xa1c39e8
   REFCNT = 1
   IV = 4
   NV = 4.748115
   PV = 0xa2f2da8 "4.748115"\0
   CUR = 8
   LEN = 36

Finally, I attempted to dump out their raw representation using the 
following code:-
     unpack("B*", pack("d",$this));

This produced:
THIS: 1001001010010110110010101101101100010001111111100001001001000000
THAT: 1001000010010110110010101101101100010001111111100001001001000000
DIFF:       ^

These are two different numbers, and perl correctly says that they are 
different when I compare them, but it prints them out as exactly the 
same number.

Now, I know very little about machine representations of floating point 
numbers, but I *guess* that this means that the numbers differ by too 
small an amount to print out, even though they do differ.

So my question to you is, should I report this as a bug somewhere, or 
should I just ignore it as "floating point weirdness"?


Dan Rowles
Outcome Technologies Ltd
BUPA House, 15-19 Bloomsbury Way, London WC1A 2BA
Registered in England, No: 3829851

More information about the mailing list