Questions about PHP floating point precision
C language and C# language, the data of floating point type is stored using single precision type (float) and double precision type (double). Float data occupies 32 bits. Double data occupies 64 bits. When we declare a variable float f= 2.25f, how do we allocate memory? If it is allocated randomly, wouldn't the world be in chaos? In fact, both float and double comply with IEEE specifications in terms of storage methods. Float complies with IEEE R32.24, while double complies with R64.53.
Whether it is single precision or double precision, storage is divided into three parts:
Sign bit (Sign): 0 represents positive, 1 represents negative
Exponent Bit (Exponent): used to store exponent data in scientific notation, and uses shift storage
Mantissa part (Mantissa): mantissa part
This article mainly introduces PHP floating point numbers Summary of precision issues. This article focuses on the problem of PHP floating point precision loss. It uses three paragraphs to explain the causes and solutions to this problem in different ways. Friends in need can refer to the following
1. PHP The problem of floating point precision loss
First look at the following code:
The code is as follows:
$f = 0.57; echo intval($f * 100); //56
The result may be a bit surprising to you, PHP Follow IEEE 754 double precision:
Floating point number, with 64-bit double precision, is represented by 1 sign bit (E), 11 exponent bits (Q), and 52 mantissa (M) (64 bits in total) .
Sign bit: The highest bit indicates the sign of the data, 0 indicates a positive number, and 1 indicates a negative number.
Exponent bit: represents the power of the data with base 2, and the exponent is represented by an offset code.
Mantissa: represents the valid digits after the decimal point of the data.
Let’s take a look at how decimals are represented in binary:
Multiply by 2 and round up, arrange in order, that is, multiply the decimal part by 2, then take the integer part, continue to multiply the remaining decimal part by 2, then take the integer part, and the remaining decimal part The part is multiplied by 2 again until the decimal part is taken. However, if a decimal like 0.57 is multiplied like this, the decimal part cannot be 0. The decimal representation of significant digits is infinite in binary.
The binary representation of 0.57 is basically (52 bits): 0010001111010111000010100011110101110000101000111101
If there are only 52 bits, 0.57 => 0.56999999999999995
No It’s hard to see the unexpected result above. .
2. Precision problem of PHP floating point numbers
Let’s look at the problem first:
The code is as follows:
$f = 0.58; var_dump(intval($f * 100)); //为啥输出57
I believe that many students have had such questions.
For the specific principle, you can read an article by "Brother Bird", where there is a detailed explanation: A FAQanswer to PHP floating point numbers
So how to avoid this What kind of problem?
There are many ways, here are two:
1. sprintf
The code is as follows:
substr(sprintf("%.10f", ($a/ $b)), 0, -7);
2. round (note that it will be Rounding)
The code is as follows:
round($a/$b, 3);
Or if you have a better way, please leave a message and tell me.
3. Answer to a common question about PHP floating point numbers
Regarding PHP floating point numbers, I have written an article before: What you should know about PHP floating point numbers (All 'bogus' about the float in PHP)
However, I missed one thing at the time, which is the answer to the following common question:
The code is as follows:
<?php $f = 0.58; var_dump(intval($f * 100)); //为啥输出57 ?>
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 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, with a length of 64 bits ( Double precision) as an example, it will be represented by 1 sign bit (E), 11 exponent bits (Q), and 52 mantissas (M) (a total of 64 bits).
Sign bit: The highest bit represents the data Positive or negative, 0 represents a positive number, 1 represents a negative number.
Exponent bit: represents the power of the data with base 2, and the exponent is represented by an offset code
Mantissa: represents the valid digits after the decimal point of the data.
The key points here It lies in the representation of decimals in binary. Regarding how to represent decimals in binary, you can search on Baidu. I will not go into details here. The key thing we need to understand is that for binary representation, 0.58 is an infinitely long value (the numbers below Omitting the implicit 1).. The binary representation of
0.58 is basically (52 bits): 0010100011110101110000101000111101011100001010001111 The binary representation of
0.57 (52 bits) is basically: 0010001111010111 000010100011110101110000101000111101
And two Or binary, if calculated only through these 52 bits, they are:
Copy code The code is as follows:
0.58 -> 0.57999999999999996 0.57 -> 0.56999999999999995
As for 0.58 * 100 We won’t consider the specific floating-point number multiplication in detail. Those who are interested can look at (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 Got….
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"
The above is the detailed content of Questions about PHP floating point precision. For more information, please follow other related articles on the PHP Chinese website!

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 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 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 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 and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

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