RE: [PHP] Strange math results
| From: | Jeff | Date: | Tue, 28 Mar 2006 23:16:30 +0000 |
| Subject: | RE: [PHP] Strange math results | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-232785@lists.php.net to get a copy of this message | ||
> -----Original Message-----
> From: Satyam [mailto:Satyam@satyam.com.ar]
> Sent: Tuesday, March 28, 2006 17:23
> To: enugroho@spikesource.com; Jay Blanchard
> Cc: Jeff; php-general@lists.php.net
> Subject: Re: [PHP] Strange math results
>
>
> Indeed, when doing floating point math, you cannot check the
> values for
> equality, they will rarely be, you have to check whether the
> difference in
> between them is less than the error you are willing to
> accept. Floating
> point numbers are usually an approximation to the actual value and
> intermediate operations might pile up errors in each approximation in
> different ways.
>
> As an example,
>
> $third = 1/3;
>
> $third will contain 0.33333 up to a certain number of digits,
> but it won't
> last forever, as it should, theoretically.
>
> Now,
>
> $third * 3 == 1
>
> will be false, but:
>
> define('MAXERR',0.0000001);
> abs($third * 3 - 1) < MAXERR
>
> will be true.
>
> MAXERR is the error you are willing to accept in your
> calculations, for
> example, if you are using cents, give it a couple of extra
> positions so that
> roundings don't creep up to significant cents, that is, use
> MAXERR = 0.0001
> or thereabouts.
>
> Satyam
>
That explains it. Thanks!
Jeff