Page 1 of 1

Getting some strange basic math results

Posted: Thu Feb 15, 2007 12:32 am
by Sarke
This code:

Code: Select all

<?php

$x = 0.33;
$y = 1.33 - 1;

if ($x > $y)
echo '$x is larger' . "\n";
elseif ($x < $y)
echo '$x is smaller' . "\n";
else
echo 'equal' . "\n";

$x = 1.33;
$y = 2.33 - 1;

if ($x > $y)
echo '$x is larger' . "\n";
elseif ($x < $y)
echo '$x is smaller' . "\n";
else
echo 'equal' . "\n";

$x = 249.33 / 2;
$y = (499.33 - 250) / 2;

var_dump(round($x, 2));
var_dump(round($y, 2));

$x = 1.33 / 2;
$y = (2.33 - 1) / 2;

var_dump(round($x, 2));
var_dump(round($y, 2));

?>
gives me these results:

Code: Select all

$x is smaller
equal
float(124.67)
float(124.66)
float(0.67)
float(0.67)
As you can see, lines 1 and 4 have the strange results. I'm using PHP version 4.4.4 installed. I'm also aware that using something like round($x, 10) is a workaround.


I'm hoping for an answer that's not super scientific about computer hardware computations, and something other than "it's just how it is - deal with it". Isn't this something that should be fixable, like a normal bug?

Re: Getting some strange basic math results

Posted: Thu Feb 15, 2007 1:08 am
by feyd
Sarke wrote:I'm hoping for an answer that's not super scientific about computer hardware computations, and something other than "it's just how it is - deal with it". Isn't this something that should be fixable, like a normal bug?
Unfortunately, the answer you want least, is the answer you are looking for. It's not a bug.

viewtopic.php?t=47186
viewtopic.php?t=39398
viewtopic.php?t=37751

Re: Getting some strange basic math results

Posted: Thu Feb 15, 2007 2:24 am
by Sarke
feyd wrote:Unfortunately, the answer you want least, is the answer you are looking for. It's not a bug.
Well that sucks...

I wrote this little function that helps in situations like the above; hopefully someone can get some use out of it.

Code: Select all

<?php

	function safe_round($num, $round, $precision = 4)
	{
		$x = round($num, $round + $precision);
		return round($x, $round);
	}

?>