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

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl


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

SublimeText3 Linux new version
SublimeText3 Linux latest version

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

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

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