search
HomeBackend DevelopmentPHP TutorialThings you should know about PHP floating point numbers

Things you should know about PHP floating point numbers

Nov 29, 2019 am 11:12 AM
php floating point number

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!

Statement
This article is reproduced at:laruence. If there is any infringement, please contact admin@php.cn delete
Optimize PHP Code: Reducing Memory Usage & Execution TimeOptimize PHP Code: Reducing Memory Usage & Execution TimeMay 10, 2025 am 12:04 AM

TooptimizePHPcodeforreducedmemoryusageandexecutiontime,followthesesteps:1)Usereferencesinsteadofcopyinglargedatastructurestoreducememoryconsumption.2)LeveragePHP'sbuilt-infunctionslikearray_mapforfasterexecution.3)Implementcachingmechanisms,suchasAPC

PHP Email: Step-by-Step Sending GuidePHP Email: Step-by-Step Sending GuideMay 09, 2025 am 12:14 AM

PHPisusedforsendingemailsduetoitsintegrationwithservermailservicesandexternalSMTPproviders,automatingnotificationsandmarketingcampaigns.1)SetupyourPHPenvironmentwithawebserverandPHP,ensuringthemailfunctionisenabled.2)UseabasicscriptwithPHP'smailfunct

How to Send Email via PHP: Examples & CodeHow to Send Email via PHP: Examples & CodeMay 09, 2025 am 12:13 AM

The best way to send emails is to use the PHPMailer library. 1) Using the mail() function is simple but unreliable, which may cause emails to enter spam or cannot be delivered. 2) PHPMailer provides better control and reliability, and supports HTML mail, attachments and SMTP authentication. 3) Make sure SMTP settings are configured correctly and encryption (such as STARTTLS or SSL/TLS) is used to enhance security. 4) For large amounts of emails, consider using a mail queue system to optimize performance.

Advanced PHP Email: Custom Headers & FeaturesAdvanced PHP Email: Custom Headers & FeaturesMay 09, 2025 am 12:13 AM

CustomheadersandadvancedfeaturesinPHPemailenhancefunctionalityandreliability.1)Customheadersaddmetadatafortrackingandcategorization.2)HTMLemailsallowformattingandinteractivity.3)AttachmentscanbesentusinglibrarieslikePHPMailer.4)SMTPauthenticationimpr

Guide to Sending Emails with PHP & SMTPGuide to Sending Emails with PHP & SMTPMay 09, 2025 am 12:06 AM

Sending mail using PHP and SMTP can be achieved through the PHPMailer library. 1) Install and configure PHPMailer, 2) Set SMTP server details, 3) Define the email content, 4) Send emails and handle errors. Use this method to ensure the reliability and security of emails.

What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor