資料結構 - 關於PHP浮點數精度問題

來源:互聯網
上載者:User
PHP manual中說:

以十進位能夠精確表示的有理數如 0.1 或 0.7,無論有多少尾數都不能被內部所使用的二進位精確表示,因此不能在不丟失一點點精度的情況下轉換為二進位的格式。

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

為什麼在例子2和例子3中,浮點數的運算能夠保全精度呢?

回複內容:

PHP manual中說:

以十進位能夠精確表示的有理數如 0.1 或 0.7,無論有多少尾數都不能被內部所使用的二進位精確表示,因此不能在不丟失一點點精度的情況下轉換為二進位的格式。

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

為什麼在例子2和例子3中,浮點數的運算能夠保全精度呢?

又是獻上我部落格的時候了:

  • 代碼之謎(四)- 浮點數(從驚訝到思考)
  • 代碼之謎(五)- 浮點數(誰偷了你的精度?)

0.1 + 0.7 的結果是 0.7999999999999999

0.5 1.5 可以用浮點數精確的表示。

0.1 的二進位:

符號位 0 指數 01111011 (-4)位元 1.10011001100110011001101 (1.60000002384185791015625)

將這個數在轉回十進位:0.10000000149011612

0.7 的二進位:

符號位 0 指數 01111110  (-1)位元 1.01100110011001100110011 (1.39999997615814208984375)

將這個數在轉回十進位:0.699999988079071

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    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.