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.

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 originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

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.

In PHP, use the clone keyword to create a copy of the object and customize the cloning behavior through the \_\_clone magic method. 1. Use the clone keyword to make a shallow copy, cloning the object's properties but not the object's properties. 2. The \_\_clone method can deeply copy nested objects to avoid shallow copying problems. 3. Pay attention to avoid circular references and performance problems in cloning, and optimize cloning operations to improve efficiency.

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

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

WebStorm Mac version
Useful JavaScript development tools

Dreamweaver Mac version
Visual web development tools

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