Floating point calculation in php

Source: Internet
Author: User
The floating point number calculation problem in php recently encountered a very strange problem when I made a price program. I caught the problem. See the following code:

$ A = 86.1-80.0;
Echo 6.1-$;
?>

You will find that the echo result is not 0, but 5.3290705182E-15. After thinking for a long time, I couldn't find the reason. I tried it in C language and the result is normal. My colleague said that he had met before and was probably out of the real number range of PHP.

Solution: because PHP is a weak language, double quotation marks (echo 6.1-"$ a";) or echo round (6.1-$ a) are added to variable a during the above code echo ); // thanks to the method provided by Xiaoshi children's shoes.

If you know the reason, please leave a message here! :)

  Postscript: Thanks to the information provided by friend s (click here), the statement of Xiaoshi kids shoes is correct. a simple decimal score cannot be converted to a binary format if a little bit of precision is lost, floating point numbers will never be accurate to the last bit. in PHP, a simple floating point operation may lose precision, resulting in confusion in the calculation results. In this article, the result of the PHP floating point operation is 5.3290705182E-15, which is an infinite number that approaches 0. Thank you and other enthusiastic friends! Pai_^

If you use php +-*/to calculate the floating point number, you may encounter some calculation result errors, such as echo intval (0.58*100); 57 is printed instead of 58, this is actually a bug that the underlying binary of the computer cannot accurately represent floating-point numbers. it is cross-language. I also encountered this problem using python. Therefore, most languages provide precision computing class libraries or function libraries. for example, php has a high-precision BC function library. the following section describes some frequently-used high-precision BC functions.

Example

The code is as follows:
 

Why is output 57? PHP bug?

I believe many people have such questions, because there are many people who ask similar questions, not to mention bugs.php.net...

To understand this, first we need to know the floating point representation (IEEE 754 ):

Floating point number. taking the 64-bit length (double precision) as an example, one-bit sign bit (E), 11 index bit (Q), and 52-bit ending number (M) are used) (64-bit in total ).

Symbol bit: the highest bit indicates positive and negative data, 0 indicates positive data, and 1 indicates negative data.

Exponent bit: the power of data at the bottom of 2, and the exponent is represented by an offset code.

Ending number: a valid number after the decimal point of the data.

The key point here is that decimal places are represented in binary. you can refer to Baidu for how decimal places are represented in binary. I will not describe them here. we need to understand the key points, 0.58 for binary representation, it is an infinitely long value (the following number saves the implicit 1 )..

The binary representation of 0.58 is basically (52 bits): the binary representation of 00101000111101011100001010001111010111000010100011110.57 is basically (52 bits): 001000111101011100001010001111010111000010100011110 and the binary of the two, if only these 52 bits are used for calculation, 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 this Details. if you are interested, you can see the Floating point. we will look at it in a fuzzy way... 0.58*100 = 57.999999999

Then you intval It. Naturally, it's 57 ....

It can be seen that the key point of this problem is: "You seem to have a poor decimal number, but it is infinite in the binary representation of the computer"

So, no longer think this is a PHP bug. this is the case .....

The PHP float type is running +-* %/, which is inaccurate.

For example:

1.

$ A = 0.1;

$ B = 0.7;

Var_dump ($ a + $ B) = 0.8 );

The printed value is boolean false.

Why? The PHP Manual provides the following warning information for floating point numbers:

Warning

Floating point precision

Obviously, a simple decimal score is like 0.1 or 0.7. it cannot be converted to an internal binary format without losing a little precision. This results in confusion: for example, floor (0.1 + 0.7) * 10) usually returns 7 instead of the expected 8, because the internal representation of this result is similar to 7.9999999999 ....

This is related to the fact that it is impossible to accurately express certain decimal scores with limited digits. For example, decimal 1/3 is changed to 0.3333333 ....

Therefore, never believe that the result of a floating point number is accurate to the last digit, or compare whether the two floating points are equal. If higher precision is required, use any precision mathematical function or gmp function.

    

Bcadd? Add two high-precision numbers

Bccomp? Returns-1, 0, 1 after comparing two high-precision numbers.

Bcp? Division of two high-precision numbers

Bcmod? High-precision remainder

Bcmul? Multiply two high-precision numbers

Bcpow? High-precision digital multiplication

Bcpowmod? Evaluate the modulo of high-precision numbers, which is very common in number theory.

Bcscale? The default number of decimal places is configured, which is equivalent to "scale =" in Linux bc"

Bcsqrt? Calculate the square root of a precise number

Bcsub? Subtract two high-precision numbers

Sorted out some instances

The php BC high-precision function library includes: addition, comparison, division, subtraction, remainder, multiplication, and npower. the default number of decimal places is configured and the square is obtained. These functions are useful when it comes to money computing, such as e-commerce price calculation.

/*** Comparison of two high-precision numbers ** @ access global * @ param float $ left * @ param float $ right * @ param int $ scale the exact number of decimal places ** @ return int $ left = $ right returns 0 | $ left <$ right Returns-1 | $ left> $ right returns 1 */var_dump (bccomp ($ left = 4.45, $ right = 5.54, 2 )); //-1/*** add two high-precision numbers ** @ access global * @ param float $ left * @ param float $ right * @ param int $ scale the exact number of decimal places ** @ return string */var_dump (bcadd ($ left = 1.0321456, $ right = 0.0243456, 2 )); // 1.04/*** subtract two high-precision values ** @ access global * @ param float $ left * @ param float $ right * @ param int $ scale the exact number of decimal places * * @ return string */var_dump (bcsub ($ left = 1.0321456, $ right = 3.0123456, 2 )); //-1.98/*** division of two high-precision numbers ** @ access global * @ param float $ left * @ param float $ right * @ param int $ scale precise to the number of decimal places ** @ return string */var_dump (bcp ($ left = 6, $ right = 5, 2 )); // 1.20/*** multiply two high-precision numbers ** @ access global * @ param float $ left * @ param float $ right * @ param int $ scale the exact number of decimal places * * @ return string */var_dump (bcmul ($ left = 3.1415926, $ right = 2.4569874566, 2 )); // 7.71/*** set the number of decimal places of the bc function ** @ access global * @ param int $ scale precise to the decimal places ** @ return void */bcscale (3); var_dump (bcp ('20140901', '6. 55957 '); // 16.007

Note: For the set number of digits, the excess part is discarded rather than rounded up.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.