Re: Simple math failing - PHP Bug?

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



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@xxxxxxxxxxxxxxx> wrote in message 
news:4185C110.9050106@xxxxxxxxxxxxxxxxxx
> 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 

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux