Why is floating point subtraction in PHP different from C
C code
#include <stdio.h>
union
{
float f;
unsigned int u;
} myun;
int main ( void )
{
float a,b,c;
a= 4501.490234;
b= 4501;
c=a-b;
myun.f=a; printf("0x%08X %f\n",myun.u,myun.f);
myun.f=b; printf("0x%08X %f\n",myun.u,myun.f);
myun.f=c; printf("0x%08X %f\n",myun.u,myun.f);
return(0);
}
Result:
0x458CABEC 4501.490234
0x458CA800 4501.000000
0x3EFB0000 0.490234
My PHP code:
<?php
$a = 4501.490234;
$b = 4501;
$c = $a - $b;
echo bin2hex(pack("f", $a))."\n";
echo bin2hex(pack("f", $b))."\n";
echo bin2hex(pack("f", $c))."\n";
$r = unpack('ffloat',"\x00\x00\xFB\x3E");
echo $r['float']."\n";
And the result:
ecab8c45
00a88c45
f3fffa3e
0.490234375
So there are two problems.
1. Different results of subtraction: f3fffa3e and 0x3EFB0000
2. Even the same 0x3EFB0000 has different representations: 0.490234375 and 0.490234
+3
source to share