Data structure-about PHP floating point accuracy problem

Source: Internet
Author: User
PHP manual says:

A rational number that can be accurately represented in decimal, such as 0.1 or 0.7, cannot be converted to a binary format without losing a little bit of precision, regardless of how many of the mantissa can be accurately represented by the binary used internally.

// example1$float = (0.1 + 0.7) * 10;echo (integer) $float;            // 7echo floor($float);               // 7// example2echo (integer) (1.5+1.5);         // 3echo floor(1.5+1.5);              // 3// example3echo (integer) (0.5*10);          // 5echo floor(0.5*10);               // 5

Why in Example 2 and Example 3, floating-point numbers and operations can preserve precision?

Reply content:

PHP manual says:

A rational number that can be accurately represented in decimal, such as 0.1 or 0.7, cannot be converted to a binary format without losing a little bit of precision, regardless of how many of the mantissa can be accurately represented by the binary used internally.

// example1$float = (0.1 + 0.7) * 10;echo (integer) $float;            // 7echo floor($float);               // 7// example2echo (integer) (1.5+1.5);         // 3echo floor(1.5+1.5);              // 3// example3echo (integer) (0.5*10);          // 5echo floor(0.5*10);               // 5

Why in Example 2 and Example 3, floating-point numbers and operations can preserve precision?

It's time to present my blog again:

    • Code Puzzle (iv)-floating point (from surprise to thinking)
    • Code Puzzle (v)-floating point number (who stole your accuracy?) )

0.1 + 0.7The result is0.7999999999999999

0.51.5you can use floating-point numbers for precise representations.

0.1The binary:

符号位 0 指数 01111011 (-4)位数 1.10011001100110011001101 (1.60000002384185791015625)

Put this number back in decimal:0.10000000149011612

0.7The binary:

符号位 0 指数 01111110  (-1)位数 1.01100110011001100110011 (1.39999997615814208984375)

Put this number back in decimal:0.699999988079071

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