Things you should know about PHP floating point numbers
All 'bogus' about the float in PHP you should know
PHP is a weakly typed language. Such a feature must have Seamlessly transparent implicit type conversion, PHP uses zval internally to save any type of value. The structure of zval is as follows (5.2 as an example):
struct _zval_struct { /* Variable information */ zvalue_value value; /* value */ zend_uint refcount; zend_uchar type; /* active type */ zend_uchar is_ref; };
In the above structure, the actual value itself is the zvalue_value union. :
typedef union _zvalue_value { long lval; /* long value */ double dval; /* double value */ struct { char *val; int len; } str; HashTable *ht; /* hash table value */ zend_object_value obj; } zvalue_value;
Today’s topic, we only focus on two members, lval and dval. We must realize that long lval has an indefinite length depending on the word length of the compiler and OS. It has It may be 32bits or 64bits, and double dval (double precision) is stipulated by IEEE 754. It is fixed length and must be 64bits.
Please remember this, which makes some PHP codes "non-platform independent" "property". Our following discussion, unless otherwise specified, assumes that long is a 64bits
IEEE 754 floating-point counting method. I will not quote it here. If you are interested, you can check it out for yourself. The key One point is that the mantissa of double is stored in 52 bits. Counting the hidden 1 significant bit, the total is 53 bits.
Here, an interesting question arises. Let’s use c code as an example (assuming long is 64bits):
long a = x; assert(a == (long)(double)a);
Excuse me, when the value of a is within what range, can the above code be asserted to be successful? (Leave the answer at the end of the article)
Now we return to the topic, PHP Before executing a script, you first need to read the script and analyze the script. This process also includes zvalizing the literals in the script. For example, for the following script:
<?php $a = 9223372036854775807; //64位有符号数最大值 $b = 9223372036854775808; //最大值+1 var_dump($a); var_dump($b);
Output:
int(9223372036854775807) float(9.22337203685E+18)
In other words, during the lexical analysis phase, PHP will judge whether a literal value exceeds the long table value range of the current system. If not, it will use lval to save it, and zval will be IS_LONG. Otherwise, it will use lval to save it. Just use dval to represent it, zval IS_FLOAT.
We must be careful with any value larger than the largest integer value, because it may cause loss of accuracy:
<?php $a = 9223372036854775807; $b = 9223372036854775808; var_dump($a === ($b - 1));
The output is false.
Now to continue the discussion at the beginning, as mentioned before, PHP's integers may be 32-bit or 64-bit, so it is decided that some codes that can run normally on 64-bit may fail due to invisible Type conversion causes precision loss, causing the code to not run properly on 32-bit systems.
So, we must be wary of this critical value. Fortunately, this critical value has been defined in PHP:
<?php echo PHP_INT_MAX; ?>
Of course, to be safe, we should use strings to save large integers, and use mathematical function libraries such as bcmath to perform calculations.
In addition, there is a key configuration that will make We are confused. This configuration is php.precision. This configuration determines how many significant bits PHP outputs when it outputs a float value.
Finally, let’s look back at the question raised above, which is a long What is the maximum value of an integer to ensure that the precision will not be lost when converted to float and then converted back to long?
For example, for an integer, we know that its binary representation is, 101. Now, let us Shift two bits to the right to become 1.01, discard the implicit significant bit 1 of the high bit, and we get the binary value of 5 stored in the double:
0/*符号位*/ 10000000001/*指数位*/ 0100000000000000000000000000000000000000000000000000
5’s binary representation, which is saved in the The mantissa part, in this case, is converted from double back to long without loss of precision.
We know that double uses 52 bits to represent the mantissa. Counting the implicit first 1, there is a total of 53 bits of precision. Then it can be concluded that if the value of a long integer is less than:
2^53 - 1 == 9007199254740991; //牢记, 我们现在假设是64bits的long
, then this integer will not lose precision when the long->double->long value conversion occurs.
Recommended: "PHP Tutorial"
The above is the detailed content of Things you should know about PHP floating point numbers. 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.

In PHP, password_hash and password_verify functions should be used to implement secure password hashing, and MD5 or SHA1 should not be used. 1) password_hash generates a hash containing salt values to enhance security. 2) Password_verify verify password and ensure security by comparing hash values. 3) MD5 and SHA1 are vulnerable and lack salt values, and are not suitable for modern password security.

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 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 type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.

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