Getting some strange basic math results

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Sarke
Forum Newbie
Posts: 11
Joined: Thu Feb 15, 2007 12:12 am

Getting some strange basic math results

Post 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?
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Re: Getting some strange basic math results

Post 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
Sarke
Forum Newbie
Posts: 11
Joined: Thu Feb 15, 2007 12:12 am

Re: Getting some strange basic math results

Post 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);
	}

?>
Post Reply