Weird PHP floating point behavior - php

Having weird problem:
$testTotal = 0;
foreach($completeBankArray as $bank){
var_dump($testTotal);
echo " + ";
var_dump(floatval($bank["amount"]));
echo " = ".(floatval($testTotal) + floatval($bank["amount"]))."</br>";
$testTotal = floatval(floatval($testTotal) + floatval($bank["amount"]));
And this is output I get:
------------------//--------------------
float(282486.09) + float(15) = 282501.09
float(282501.09) + float(3.49) = 282504.58
float(282504.58) + float(22.98) = 282527.55999999
float(282527.55999999) + float(5.2) = 282532.76
float(282532.76) + float(39.98) = 282572.73999999
float(282572.73999999) + float(2.6) = 282575.33999999
float(282575.33999999) + float(2.99) = 282578.32999999
------------------//-----------------------
How is this possible, what am I doing wring ?

You aren't doing anything wrong. Floats are notoriously innaccurate. From the docs (In the huge red warning box):
Floating point numbers have limited precision. Although it depends on the system, PHP typically uses the IEEE 754 double precision format, which will give a maximum relative error due to rounding in the order of 1.11e-16. Non elementary arithmetic operations may give larger errors, and, of course, error propagation must be considered when several operations are compounded.
Additionally, rational numbers that are exactly representable as floating point numbers in base 10, like 0.1 or 0.7, do not have an exact representation as floating point numbers in base 2, which is used internally, no matter the size of the mantissa. Hence, they cannot be converted into their internal binary counterparts without a small loss of precision. This can lead to confusing results: for example, floor((0.1+0.7)*10) will usually return 7 instead of the expected 8, since the internal representation will be something like 7.9999999999999991118....
So never trust floating number results to the last digit, and do not compare floating point numbers directly for equality. If higher precision is necessary, the arbitrary precision math functions and gmp functions are available.

Floats are never exact and will diff quite a bit in the long run. If you are working with precision math, please read about the bc library.

Classic numeric precision example. Computers store floating point numbers in binary.
The short answer is that the computer cannot accurately represent some floating point numbers in binary.
The long answer involves moving between numerical bases. If you have a float, you cannot represent it completely in binary unless the denominator contains can be broken into factors that are powers of 2.

The other answers have given some insight into why you get this behaviour with floats.
If you are dealing with money, one solution to your problem would be to use integers instead of floats, and deal with cents instead of dollars. Then all you need to do is format your output to include the decimal.

Related

Does the value of floatval('a.bc') exactly equals to abc/100?

For example, I know 0.1 is not accurate due to floating point rounding error, however, I have another question: does
$num=floatval('0.1');
exactly equals to
$num=1/10
? Do 2 $num above rounds to the same value finally?
or in general, does
$num=floatval('a.bc');
exactly equals to
$num=abc/100;
(which abc are digits, and abc are integers)?
To my knowledge, PHP does not have an official standard. Such documentation as there is does not fully specify the semantics of floating-point operations. It does not specify which floating-point representation or format implementations must use.
That said, good practice in floating-point operations is for an operation to produce a result as if the result were first computed with infinitely precise arithmetic (exact mathematics) and then rounded according to the rounding rule in effect. (Most commonly, the rule used is to round to the nearest representable value and to round ties to the nearer value with an even low digit.)
If that rule is used, then the operation of converting the decimal numeral a.bc to floating-point should yield exactly the same result as dividing the number abc by 100. This is because the exact mathematical result of interpreting a.bc as decimal equals the exact mathematical result of dividing abc by 100, so they both produce exactly the same result before rounding, and rounding should round them to the same representable value.
In some programming languages, such as C and C++, floating-point expressions are permitted to be evaluated with more precision than the nominal type, and floating-point expressions are permitted to be contracted, meaning that multiple operations can be combined into a single operation that would be equivalent mathematically.
An example of the former is that a programming language implementation might use double for doing arithmetic with values that are nominally of type float. If a PHP implementation did this, then a.bc might effectively have a different value from abc/100 because one is computed with float precision while the other is computed with double precision. If a particular PHP implementation is implemented using C or C++, this variation in precision could happen because the underlying C or C++ implementation does it, as permitted by the C and C++ standards.
An example of the latter is that, when computing a*b + c, some C or C++ implementations may choose to use an instruction that produces a result as if a*b + c were fully computed with exact mathematics and then rounded to the nearest representable value instead of first computing a*b and rounding it, then adding c to the rounded result and rounding a second time. I have not seen indication that PHP implementations do this. However, if they do, then it is possible that interpreting .abc as a decimal numeral and dividing abc by 100 may appear to have different results in some circumstances where extra precision is used or where they are combined with other operations.
Note that, if an implementation is using extra precision and/or contractions, the problem is not just that a.bc might have different value than abc/100. The expression abc/100 might appear to have different values from itself in different situations, as the implementation might use different precisions in different situations.

Prevent php from rounding small numbers

Can php handle extremely small numbers without rounding them? For example, when calculating exp(-99) + 1/2, php compute this to be 0.5. This is problematic if later I want to multiply the given result, instead of an extremely small number, it just gives half the number.
echo exp(-99) + 1/2 // Outputs 0.5
You're out of the range supported by floating point numbers.
On my platform (PHP floats are 64 bit) echo exp(-99); returns currectly 1.0112214926104E-43
That's because the exponential part is wide enought to represent e^-99
But as I add... echo exp(-99)+0.5; I get 0.5
The result you expect would be something with more than 50 decimal digits.
Double floats doesn't have a such large mantissa (usually the limit is around 18-20 decimals).
To answer your question, If you really need to do such math (handle extremely small numbers without rounding them) you could use PHP's arbitrary precision math extension:
http://php.net/manual/en/book.bc.php

PHP & Base 2. Which Floats give a precise Value?

Apologies for my poor maths skills, I've tried to understand this to answer my own query but I'm not convinced.
We all know that PHP doesn't store Floats in base 10 but base 2.
I have a series of calculations that are using 0.5 as the only float, and in trying to understand if they will be stored as 0.500001 or 0.4999999 (for rounding purposes there is a big difference!!!) I have come to understand that 0.5 will be stored precisely in base2.
My queries are
A Have I understood this correctly?
B What other floats are stored precisely in base2? eg 0.25?
Any multiple of 1/pow(x, 2) can be precisely represented as a float.
That means x/2, x/4, x/8, x/16 ...ect. can be accurately represented.
For more information on how floating point numbers are store see http://kipirvine.com/asm/workbook/floating_tut.htm
Gmp is a good library for high precision math.
PHP is not required to use binary floating-point. It depends on the system.
Many systems use IEEE-754 binary floating-point (sometimes incompletely or with modifications, such as flushing subnormal numbers to zero).
In IEEE-754 64-bit binary floating point, a number is exactly representable if and only if it is representable as an integer F times a power of two, 2E, such that:
The magnitude of F is less than 253.
–1074 ≤ E < 972.
For example, ½ equals 1•2–1. 1 is an integer under the integer limit, and –1 is an exponent within the exponent limits. So ½ is representable.
253+1 is not representable. As it is, it is an integer outside the integer limit. If you try to scale it by a power of two to bring it within the limit, you get a number that is not an integer. So there is no way to represent this value exactly in IEEE-754 64-bit binary floating-point.
1/3 and 1/10 are also not representable because no matter what power of two you scale them by, you will not produce an integer.

Wrong Calculation? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Is double Multiplication Broken in .NET?
PHP unexpected result of float to int type cast
echo (int) ( (0.1+0.7) * 10);
Gives me answer 7 but not 8.
echo (int) ( (0.1+0.8) * 10);
Gives answer 9 which is right
whats wrong? can anybody explain
thanx,
-Navi
It’s normal – There’s a thing called precision while working with floating point numbers. It’s present in most of the modern languages. See here: http://www.mredkj.com/javascript/nfbasic2.html for more information.
((0.1+0.7) * 10) is probably something like 7.9999999 and (int) 7.9999999 = 7
On the other hand ((0.1+0.8) * 10) is probably 9.00000001 and (int)9.00000001 = 9
Floating point numbers have limited precision. Although it depends on the system, PHP typically uses the IEEE 754 double precision format, which will give a maximum relative error due to rounding in the order of 1.11e-16. Non elementary arithmetic operations may give larger errors, and, of course, error propagation must be considered when several operations are compounded.
Additionally, rational numbers that are exactly representable as
floating point numbers in base 10, like 0.1 or 0.7, do not have an
exact representation as floating point numbers in base 2, which is
used internally, no matter the size of the mantissa. Hence, they
cannot be converted into their internal binary counterparts without a
small loss of precision. This can lead to confusing results: for
example, floor((0.1+0.7)*10) will usually return 7 instead of the
expected 8, since the internal representation will be something like
7.9999999999999991118....
So never trust floating number results to the last digit, and do not
compare floating point numbers directly for equality. If higher
precision is necessary, the arbitrary precision math functions and gmp
functions are available.
Source: http://php.net/manual/en/language.types.float.php
try
echo (float) ( (0.1+0.7) * 10);
Use Float
echo (float) ( (0.1+0.7) * 10);
it will give you perfect ans
try
echo (int) round( ( (0.1+0.7) * 10));
This should compensate the floating point computation error.

PHP integer rounding problems

echo (int) ( (0.1+0.7) * 10 );
Why does the above output 7? I understand how PHP rounds towards 0, but isn't (0.1+0.7) * 10 evaluated as a float and then casted as an integer?
Thanks!
There's a loss in precision when decimals are converted internally to their binary equivalent. The computed value will be something like 7.9+ instead of the expected 8.
If you need a high degree of accuracy, use the GMP family of functions or the bcmath library.
See the manual:
http://php.net/manual/en/language.types.float.php
It is typical that simple decimal
fractions like 0.1 or 0.7 cannot be
converted into their internal binary
counterparts without a small loss of
precision. This can lead to confusing
results: for example,
floor((0.1+0.7)*10) will usually
return 7 instead of the expected 8,
since the internal representation will
be something like 7.9.
The other answers explained WHY this happens. This should get you what you want:
echo (int) round( (0.1+0.7) * 10 );
Just round the float before casting it to an int.
I don't have php installed, but in python:
$ python
>>> 0.1+0.7
0.79999999999999993
>>>
Not all numbers in base 10 can be represented precisely in base 2 system. Check Wikipedia article:
http://en.wikipedia.org/wiki/Binary_numeral_system
section Fractions in Binary. In particular, this line:
Fraction Decimal Binary Fractional Approx.
1/10 0.1 0.000110011... 1/16+1/32+1/256...
1/10 cannot be represented in a finite way in base 2. Thus, 0.1 + 0.7 cannot be precisely calculated in base 2.
Never assume floating-point calculations are precise, it will bite you sooner or later.
1/10 cannot be represented in a finite number of binary digits, just like 1/3 cannot be represented as a finite number of base-10 digits. Therefore you are actually adding together 0.09999999999999... and 0.69999999999999... -- the sum is almost 8, but not quite.

Categories