Let's talk about php floating point exact calculation, php floating point number
Bc is short for Binary Calculator. Bc * function parameters are all operands plus an optional [int scale], such as string bcadd (string $ left_operand, string $ right_operand [, int $ scale]). If scale is not provided, use the default value of bcscale. Here, the large number is represented by a string consisting of 0-9, and the return value is also a string.
Bcadd-add two high-precision numbers
Bccomp-compare two high-precision numbers and return-1, 0, 1
Bcdiv-division of two high-precision numbers
Bcmod-precise digital Remainder
Bcmul-multiply two high-precision numbers
Bcpow-calculate a high-precision digital Multiplier
Bcpowmod-modulus of high-precision multiplication of numbers, which is very common in number theory.
Bcscale-the default number of decimal places configured, which is equivalent to "scale =" in Linux bc"
Bcsqrt-calculate the square root of a precise number
Bcsub-Subtract two high-precision numbers
First, let's look at a piece of code:
<?php$a = 0.1;$b = 0.7;var_dump(($a + $b) == 0.8);
The printed value is boolean false.
Why? The PHP Manual provides the following warning information for floating point numbers:
Floating point Precision
Obviously, a simple decimal score is like 0.1 or 0.7. It cannot be converted to an internal binary format without losing a little precision. This will lead to chaotic results: for example, floor (0.1 + 0.7) * 10) usually returns 7 instead of 8 in expectation, because the internal representation of the result is similar to 7. 9999999999 ....
This is related to the fact that it is impossible to accurately express certain decimal scores with limited digits. For example, decimal 1/3 is changed to 0.3333333 ....
Therefore, never believe that the result of a floating point number is accurate to the last digit, or compare whether the two floating points are equal. If higher precision is required, use any precision mathematical function or gmp function.
Then we should rewrite the formula above
<?php$a = 0.1;$b = 0.7;var_dump(bcadd($a,$b,2) == 0.8);
This solves the problem of floating point calculation.
Articles you may be interested in:
- Introduction to integer and floating point numbers of PHP Data Types
- Use of the sprintf function in php to control the floating point format
- How to compare and integer inaccuracy of floating point numbers in PHP
- Php's method of determining whether two floating point numbers are equal
- PHP floating point number Accuracy Problem Summary
- You should know about PHP floating point
- Analysis of Two float (floating point number) Comparison instances in PHP
- PHP floating point number FAQ