Re: Simple math failing - PHP Bug?
| From: | Aidan Lister | Date: | Mon, 01 Nov 2004 12:09:09 +0000 |
| Subject: | Re: Simple math failing - PHP Bug? | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-200824@lists.php.net to get a copy of this message | ||
We have a chapter in the manual about this,
http://www.php.net/manual/en/language.types.float.php
This is also interesting:
http://docs.python.org/tut/node15.html
Kind Regards,
Aidan
"Brian T. Allen" <brian@gzmarketing.com> wrote in message
news:4185C110.9050106@gzmarketing.com...
> Hi,
>
> OK, I'm totally stumped by this. This should be the simplest math
> imaginable (addition and subtraction), but PHP is coming up with the wrong
> answer!
>
> I've checked on 3 different machines (all linux) running both PHP 4 and
> PHP 5.
>
> Here is the code to duplicate the problem:
>
> -----------------------------------
> <?php
>
> $a = 2503.54;
> $b = 303.55;
> $c = 202.13;
>
> $total = 0;
> $total += $a;
> $total += $b;
> $total += $c;
>
> $added_total = $total;
>
> echo "$a + $b + $c = $total<br>";
> echo "Actual: $total<br><br>";
>
> $total -= $a;
> $total -= $b;
> $total -= $c;
>
> echo "$added_total - $a - $b - $c = 0<br>";
> echo "Actual: $total<br><br>";
>
> ?>
> -----------------------------------
>
> This ~should~ output this:
>
> 2503.54 + 303.55 + 202.13 = 3009.22
> Actual: 3009.22
>
> 3009.22 - 2503.54 - 303.55 - 202.13 = 0
> Actual: 0
>
> But instead it outputs this:
>
> 2503.54 + 303.55 + 202.13 = 3009.22
> Actual: 3009.22
>
> 3009.22 - 2503.54 - 303.55 - 202.13 = 0
> Actual: 2.84217094304E-13
>
>
> Now I'm the first to admit that 0.000000000000284217094304 and 0 are
> really very close, but when you are testing a variable to see if it equals
> 0, it is the difference between true and false.
>
> This seems very, very basic to me, but I can't find the flaw in my code.
>
> Is this legitimately bad math on the part of PHP?
>
> Thanks,
> Brian