This question already has answers here:
Closed 12 years ago.
Possible Duplicates:
Why does 99.99 / 100 = 0.9998999999999999
Dealing with accuracy problems in floating-point numbers
I've seen this issue in php and javascript. I have this number: float 0.699
if I do this:
0.699 x 100 = 69.89999999999999
why?
edit
round(0.699 x 10, 2): float 69.90000000000001
Floating point arithmetic is not exact.
See Floating point on Wikipedia for a deeper discussion of the problem.
This is what has helped me in the past. It has a lot to do with how things are represented in binary. Basically long story short in binary there isn't an exact number for all real numbers of large numbers.
The link below will describe that in more detail for you.
What Every Computer Scientist Should Know About Floating-Point Arithmetic
This will happen in any language. Floats, like everything else on a computer, are stored as binary. The number 0.699, while representable exactly in decimal, is probably a repeating decimal in binary, so it can't be stored to exact precision.
Check out the wikipedia entry for how floats are stored, and why this happens.
Javascript numbers are floating point.
Take a look at The complete javascript number reference. Excerpt:
All numbers in Javascript are 64bit (8
bytes) floating point numbers which
yields an effective range of 5e-324
(negative) to 1.7976931348623157e+308
(positive) at the time this article
was written (this may eventually
change to 128 bits in the future as 64
bit processors become commonplace and
the ECMA standards evolve).
Integers are considered reliable
(numbers without a period or exponent
notation) to 15 digits (9e15) 1.
Floating point numbers are considered
only as reliable as possible and no
more! This is an especially important
concept to understand for currency
manipulation as 0.06 + 0.01 resolves
to 0.06999999999999999 instead of
0.07.
Take a look at Floating Point, specifically the section on IEEE 754 and representable numbers.
This behavior can be reproduced in many programming languages, including C++ and Assembly. The reason is floating point format using by FPU. You can read details here:
http://www.arl.wustl.edu/~lockwood/class/cs306/books/artofasm/Chapter_14/CH14-1.html#HEADING1-19
General rule: never expect exact result of floating-point operations. Never compare two floating point numbers, use interval, for example: instead of testing f1 == f2, use f1 > (f2 -e) and f1 < ( f2 + e ), e is some small value.
Related
When developing calculator in PHP 5+, can programmer get results without thinking on errors of rounding and imprecise representation of decimal numbers?
I mean built-in perfect ways to get, for example, results with given accuracy.
Or each operation like $x = $y * $z + 0.77 must require to develop additional checks in algorithm like rounding (for avoiding errors)?
So errors or imprecision - is up to PHP built-in core or up to developer?
PHP 7 has 64-bit support, what is the improvement on this direction (accuracy of calculations)?
When developing calculator in PHP 5+, can programmer get results without thinking on errors of rounding and imprecise representation of decimal numbers?
Simple answer is No.
Doing arithmetics on decimal basis by using a binary machine like a computer can and will always produce some kind of error.
Many details are explained in this article, it's quite a complex subject.
http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html
Simple example from the decimal world:
The fraction 1/3 can not be expressed as a finite floating point number in decimal notation. Often we try it by writing 0.333333333... but that's not 100% accurate.
Same applies to binary number arithmetics.
[Edit]
If you need a very high degree of precision than you should have a look at phps BC math functions http://php.net/manual/en/ref.bc.php
I don't think there's anything in PHP 7 that will change this. AS #maxhb points out, doing floating point arithmetic is inherently imprecise so you must mind rounding errors.
The 64-bit capability does not fundamentally change this.
This question already has answers here:
Unexpected results when working with very big integers on interpreted languages
(36 answers)
Working with large numbers in PHP
(8 answers)
Closed 9 years ago.
using php, this code echo sprintf('%.9F',pow(3,47)); outputs 26588814358957501972480.000000000
where as other sites like this gives 3^47 = 26588814358957503287787. Is there any bug with PHP? How to resolve it?
btw, i'd like to know what is the maximum digit php can handle for calculation using pow,sprintf,fmod. Is it 300 digits?
You need to use an external program or a PHP extension (library).
I've just tested it with BC Math and GMP using the bcpow()/gmp_pow() functions and it works perfectly:
<?php
// both output 26588814358957503287787
echo bcpow('3', '47');
echo gmp_strval( gmp_pow('3', '47') );
The PHP.net documentation has a nice section about that topic:
Floating point precision
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.
For a "simple" explanation, see the » floating point guide that's also
titled "Why don’t my numbers add up?"
— http://php.net/manual/en/language.types.float.php
Note that the php.ini configuration value 'precision' can also modify the precision when converting from floats to strings.
bcpow() (a function of the BCMath Arbitrary Precision Mathematics library) can be used in this case.
echo bcpow('3', '47'); //as mentioned in ComFreek's answer
//outputs 26588814358957503287787
The reason why pow isn't work here is because pow() uses float, and there's a size limitation for float.
See this excerpt from the PHP Manual:
The size of a float is platform-dependent, although a maximum of ~1.8e308 with a precision of roughly 14 decimal digits is a common value (the 64 bit IEEE format)
In other words, the maximum possible size may vary -- i.e. (may be different for 32-bit, and 64-bit systems).
Hope that answers your question!
$a = 100;
$b = 3;
$test1 = $a/ $b;
$test2 = 33.333333333333; // $test2 == $test1
var_dump(($test1 * $b)); // float(100)
var_dump(($test2 * $b)); // float(99.999999999999)
Any explanation for that ?
100/3 results in 33.3-repeating.
There is no decimal point value that will ever show it. In maths, such a number is normally shown by a little dot over the repeating value. (though I have no idea how to show that in this code box).
Refer to this wiki article to see how they are represented in various places and a much more detailed explanation that I have given here.
However, from the article here is a snippet of the summary:
In arithmetic, repeating decimal is a way of representing a rational number. Thus, a decimal representation of a number is called a repeating decimal (or recurring decimal) if at some point it becomes periodic, that is, if there is some finite sequence of digits that is repeated indefinitely. For example, the decimal representation of 1/3 = 0.3333333… or 0.3 (spoken as "0.3 repeating", or "0.3 recurring") becomes periodic just after the decimal point, repeating the single-digit sequence "3" infinitely. A somewhat more complicated example is 3227/555 = 5.8144144144…, where the decimal representation becomes periodic at the second digit after the decimal point, repeating the sequence of digits "144" indefinitely.
Now, that's the crux of your issue here, but also keep in mind (as the other two answers point out) that floats are amazingly innacurate in terms of calculations and comparisons. A quick search of this site will reveal a small army of people that have had problems with the internal representations of floats - mainly which resulted in unexpected behavior when doing comparisons.
Take a long read of the PHP warning on the float data type - again I have copied the important bit here:
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....
Not all floats can be represented exactly by processor. $a/$b is one of them.
So, $test1 != $test2 is true.
Information from PHP
Warning
Floating point precision
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.
As noted in the warning above, testing floating point values for equality is problematic, due to the way that they are represented internally. However, there are ways to make comparisons of floating point values that work around these limitations.
To test floating point values for equality, an upper bound on the relative error due to rounding is used. This value is known as the machine epsilon, or unit roundoff, and is the smallest acceptable difference in calculations.
Many thanks to all who took the time to answer my question
For the following
echo 0.02-0.01-0.06+0.05;
I got result is
6.93889390391E-18
For this one
echo -0.02+0.02;
I got result
0
I want to know why i got the different result for those to. I suppose to get two 0 result.
That's how floating point numbers work.
floating point arithmetic doesn't really correlate strongly to normal mathematical rules. For example, operations aren't associative or distributive.
floating point representations are approximations with limited precision.
this isnt a php specific thing - computers simply cant represent numbers like we conceptualize them.
When you write numerals “0.02” in source code, the compiler or interpreter uses floating-point to represent them. The most common floating-point format is IEEE 754 binary floating-point, either single-precision or double-precision.
This floating-point format cannot represent most decimal numerals exactly. For example, just as decimals cannot represent 1/3 exactly (it is approximately .3333, but any decimal numeral of finite length ends somewhere, so it differs slightly from 1/3), the binary numerals used in floating-point cannot represent 1/10 exactly (in binary, 1/10 is approximately .000110011001100110011).
Therefore, when you write “0.02-0.01-0.06+0.05”, the computer is not doing arithmetic with exactly those numbers. It is using close approximations. So the result you get is a close approximation.
If you want an exact result, you must either learn the details of floating-point arithmetic so that you can craft operations that avoid error or for which the error can be corrected or you should use only integer arithmetic. For example, if the above represented dollars amounts to be added and subtracted, you could instead store penny amounts and calculate “2-1-6+5”.
If you round it to two or three decimal places, this will fix it for you.
Hi just for someone hiting this problem, you can use the arbitrary precision functions from BCMath library
http://php.net/manual/en/ref.bc.php
echo 12606.69 + 3053.46 - 15660.15;
1.8189894035459E-12
and
echo bcadd((12606.69 + 3053.46),-15660.15);
0
This question already has an answer here:
Closed 11 years ago.
Possible Duplicate:
The accuracy of PHP float calculate
when i executed the code below in eclipse , the result was not 0 but 5.5511151231258E-17
$a = 0.1+0.2-0.3;
echo $a;
could someone tell me why?
This is because floating point numbers have limited precision.
You can find more information about this trait on this page in the PHP manual.
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 progragation 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 never
compare floating point numbers for equality. If higher precision is
necessary, the arbitrary precision math functions and gmp functions
are available.
Please note that this is not a trait specific to PHP; it is just the way floating point numbers work.
You're running into PHP's floating point precision issues. All languages have them, you've just found PHP's.
This is not PHP specific, as others have mentioned. However, you can avoid limited floating point precision by using round():
<?php
$a = 0.1+0.3-0.2;
echo round($a, 2);
?>
Of course you will need to know the number of digits beforehand.
It's because computers can't accurately represent floating point numbers. This isn't specific to PHP.
See here for details.