Re: Strange math results

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

 



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



----- Original Message ----- From: "Ezra Nugroho" <enugroho@xxxxxxxxxxxxxxx>



It is not always possible to precisely represent decimal values as a
float type in binary. In these cases, the value that you have is either
slightly bigger or slightly smaller than the actual.

In your specific problem, you have two values that are not equal, but
very similar. Therefore you get a small negative value when subtracting
them.

You just have to keep this fact in mind whenever you want to do high-
precision computing.



On Tue, 2006-03-28 at 15:30 -0600, Jay Blanchard wrote:
[snip]
I've got a strange problem here.

I'm subtacting one variable from another, both of type "double" and if
they are the same, instead of getting a result of 0, I get something
like -9.99200722163E-016

Is this a bug or am I doing something wrong here?
[/snip]

From all of the information that you sent in your post I'd say that
you're doing something wrong here.


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




--
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