Floating point calculation problem in php_PHP tutorial
If you use PHP’s +-*/ to calculate floating point numbers, you may encounter some problems with incorrect calculation results. For example, echo intval(0.58*100); will print 57 instead of 58. This is actually It is a bug that the underlying binary of the computer cannot accurately represent floating point numbers. It is cross-language. I also encountered this problem when using Python. Therefore, basically most languages provide class libraries or function libraries for precise calculations. For example, PHP has a BC high-precision function library. Below, PHP training teacher Dane will introduce the use of some commonly used BC high-precision functions.
Example
代码如下 | |
Why is the output 57? Is it a PHP bug?
I believe that many students have had such questions, because there are many people asking me similar questions, not to mention that people often ask on bugs.php.net...
To understand this reason, first we need to know the representation of floating point numbers (IEEE 754):
Floating point numbers, taking 64-bit length (double precision) as an example, will be represented by 1 sign bit (E), 11 exponent bits (Q), and 52-bit mantissa (M) (a total of 64 bits).
Sign bit: The highest bit represents the sign of the data, 0 represents a positive number, and 1 represents a negative number.
Exponent bit: represents the data raised to the power of base 2, and the exponent is represented by an offset code
Mantissa: Indicates the significant digits after the decimal point of the data.
The key point here is the representation of decimals in binary. As for how decimals are represented in binary, you can search on Baidu. I won’t go into details here. The key thing we need to understand is that for binary representation, 0.58 is infinite. Long values (numbers below omit the implicit 1)..
The binary representation of 0.58 (52 bits) is basically: 00101000111101011100001010001111010111000010100011110.57 The binary representation (52 bits) is basically: 001000111101011100001010001 111010111000010100011110 And the binary numbers of the two, if calculated only through these 52 bits, are: www.111cn. net
0.58 -> 0.579999999999999960.57 -> 0.5699999999999999 As for the specific floating point multiplication of 0.58 * 100, we do not consider it in detail. Those who are interested can look at it (Floating point), we will look at it vaguely with mental arithmetic... 0.58 * 100 = 57.999999999
Then if you intval it, it will naturally be 57…
It can be seen that the key point of this problem is: "Your seemingly finite decimal is actually infinite in the binary representation of the computer"
So, don’t think this is a PHP bug anymore, this is what it is…
PHP floating point type has an inaccuracy in +-*%/
For example:
1.
$a = 0.1;
$b = 0.7;
var_dump(($a + $b) == 0.8);
The printed value is boolean false
Why is this? The PHP manual has the following warning message for floating point numbers:
Warning
Floating point precision
Apparently simple decimal fractions like 0.1 or 0.7 cannot be converted to the internal binary format without losing a bit 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, because the internal representation of the result is something like 7.9999999999….
This is related to the fact that it is impossible to express certain decimal fractions accurately with a finite number of digits. For example, 1/3 in decimal becomes 0.3333333. . .
So never believe that the floating point number result is accurate to the last digit, and never compare whether two floating point numbers are equal. If you really need higher precision, you should use arbitrary precision math functions or the gmp function
The code is as follows | |
| |
代码如下 | |
$a = 0.1; |
$a = 0.1;
$b = 0.7;
var_dump(bcadd($a,$b,2) == 0.8);<🎜>
bcadd — Add two high-precision numbers
bccomp — Compares two high-precision numbers, returns -1, 0, 1
bcdiv — divide two high-precision numbers
bcmod — Find the remainder of a high-precision number
bcmul — Multiply two high-precision numbers
bcpow — Find the power of high-precision numbers
bcpowmod — Find high-precision numerical power and modulus, very commonly used in number theory
bcscale — Configure the default number of decimal points, which is equivalent to "scale="
in Linux bcbcsqrt — Find the square root of a high-precision number
bcsub — Subtract two high-precision numbers
Organized some examples
PHP BC high-precision function library includes: addition, comparison, division, subtraction, remainder, multiplication, nth power, configure the default number of decimal points, and square. These functions are more useful when it comes to monetary calculations, such as e-commerce price calculations.
代码如下 | |
/** * 两个高精度数比较 * * @access global * @param float $left * @param float $right * @param int $scale 精确到的小数点位数 * * @return int $left==$right 返回 0 | $left<$right 返回 -1 | $left>$right 返回 1 */ var_dump(bccomp($left=4.45, $right=5.54, 2)); // -1 /** * 两个高精度数相加 * * @access global * @param float $left * @param float $right * @param int $scale 精确到的小数点位数 * * @return string */ var_dump(bcadd($left=1.0321456, $right=0.0243456, 2)); //1.04 /** * 两个高精度数相减 * * @access global * @param float $left * @param float $right * @param int $scale 精确到的小数点位数 * * @return string */ var_dump(bcsub($left=1.0321456, $right=3.0123456, 2)); //-1.98 /** * 两个高精度数相除 * * @access global * @param float $left * @param float $right * @param int $scale 精确到的小数点位数 * * @return string */ var_dump(bcdiv($left=6, $right=5, 2)); //1.20 /** * 两个高精度数相乘 * * @access global * @param float $left * @param float $right * @param int $scale 精确到的小数点位数 * * @return string */ var_dump(bcmul($left=3.1415926, $right=2.4569874566, 2)); //7.71 /** * 设置bc函数的小数点位数 * * @access global * @param int $scale 精确到的小数点位数 * * @return void */ bcscale(3); var_dump(bcdiv('105', '6.55957')); // 16.007 |
Note: Regarding the number of digits set, the excess is discarded instead of rounded.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.
