Page 1 of 1
Floating point numbers.
Posted: Sun Sep 04, 2005 10:51 pm
by wyred
A friend discovered this in VB, I did a quick test in PHP and found similar results. What could be wrong?
Here's the code:
Code: Select all
$value1 = 1;
$value2 = 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1;
echo 'Value 1:'.$value1.'<br />';
echo 'Value 2:'.$value2.'<br />';
echo ($value1 == $value2)?'same':'diff';
Output:
Value 1:1
Value 2:1
diff
Discuss! :)
Posted: Sun Sep 04, 2005 10:53 pm
by feyd
welcome to the wonderful world of floating point arithmetic errors.
Posted: Sun Sep 04, 2005 11:34 pm
by josh
I don't get it feyd, shouldn't PHP convert the integer to a float and then return true for that comparison? It's not like he used ===
can you elaborate on these errors?
Posted: Sun Sep 04, 2005 11:42 pm
by John Cartwright
Posted: Sun Sep 04, 2005 11:47 pm
by feyd
Code: Select all
[feyd@home]>php -r "$v1 = 1; $v2 = 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1; printf('%.20f|%.20f',$v1,$v2);"
1.00000000000000000000|0.99999999999999982236
[feyd@home]>php -r "$v1 = 1; $v2 = 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1; var_export(array_map('bin2hex',unpack('A8v1/A8v2',pack('d*',$v1,$v2))));"
array (
'v1' => '000000000000f03f',
'v2' => 'ffffffffffffef3f',
)
Posted: Mon Sep 05, 2005 1:06 am
by josh
Code: Select all
$v1 = 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1;
$v2 = 0.99999999999999982236;
$v3 = 1;
var_dump(bccomp($v1, $v2, 20));
var_dump(bccomp($v1, $v3, 20));
var_dump(bccomp($v2, $v3, 20));
Now that's just silly
Posted: Mon Sep 05, 2005 9:34 pm
by wyred
So what's the cause of all these errors? Anyway, here's another interesting set of results.
Code:
Code: Select all
$value3 = 0.1;
printf('Value 3: %.25f <br />',$value3);
$value3 += 0.1;
printf('Value 3: %.25f <br />',$value3);
$value3 += 0.1;
printf('Value 3: %.25f <br />',$value3);
$value3 += 0.1;
printf('Value 3: %.25f <br />',$value3);
$value3 += 0.1;
printf('Value 3: %.25f <br />',$value3);
$value3 += 0.1;
printf('Value 3: %.25f <br />',$value3);
$value3 += 0.1;
printf('Value 3: %.25f <br />',$value3);
$value3 += 0.1;
printf('Value 3: %.25f <br />',$value3);
$value3 += 0.1;
printf('Value 3: %.25f <br />',$value3);
$value3 += 0.1;
printf('Value 3: %.25f <br />',$value3);
Results:
Value 3: 0.1000000000000000000000000
Value 3: 0.2000000000000000000000000
Value 3: 0.3000000000000000444089210
Value 3: 0.4000000000000000000000000
Value 3: 0.5000000000000000000000000
Value 3: 0.6000000000000000000000000
Value 3: 0.7000000000000000000000000
Value 3: 0.7999999999999999111821580
Value 3: 0.9000000000000000000000000
Value 3: 0.9999999999999998223643161
Posted: Mon Sep 05, 2005 9:44 pm
by feyd
http://docs.sun.com/source/806-3568/ncg_goldberg.html
found by: Google :: floating point error
basically, it's an intrinsic part of using floating point values. There's nothing you can do about them other than use arbitrary length computations.