Reply to Re: [PHP] Weird results of "=="

Your name:

Reply:


Posted by "Brian P. O'Donnell" on 08/24/05 01:28

That did the trick.

Thanks a million.

Brian

"Jasper Bryant-Greene" <jasper@bryant-greene.name> wrote in message
news:430B9867.2070000@bryant-greene.name...
> Brian P. O'Donnell wrote:
> > <?
> >
> > $a = 252.73;
> > $b = 252.73;
> > $c = 0;
> >
> > if ($a == ($b + $c))
> > {
> > // do the first thing
> > }
> > elseif ($a > ($b + $c))
> > {
> > // do the second thing
> > }
> > elseif ($a < ($b + $c))
> > {
> > // do the third thing
> > }
> >
> > ?>
> >
> > Each of the three variables is derived by some earlier calculation, but
for
> > testing purposes I have made sure that they end up being $a = $b and $c
= 0.
> > I have tested for three different values (of $a) and gotten all three
> > results. That is, once the first block has executed, once the second
block
> > and once the third block.
> >
> > Am I missing something really obvious here?
>
> This is an inherent problem with floating-point operations, especially
> comparison, and is not unique to PHP. Often numbers will be off by some
> miniscule amount, just enough to make them not equal.
>
> What I would do in this situation is create a function float_equals(),
> after deciding what delta is acceptable for your situation, like this:
>
> define('MAX_FLOAT_DELTA', 0.001); // Or whatever is acceptable for you
>
> function float_equals($a, $b) {
> return (abs($a - $b) <= MAX_FLOAT_DELTA);
> }
>
> Then use float_equals($x, $y) instead of $x == $y.
>
> Jasper

[Back to original message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация