doufen3563 2015-12-29 13:26
浏览 52
已采纳

PHP:使用浮点值计数时的限制

I need to count numbers but have to use a float datatype (don't as why - it's kind of an embedded system).

The simple counter goes like:

$num=1.0;
do {
    $num = $num + 1;
    // do some stuff
    // ...
} while (...);

Question 1: What is the biggest number that can be counted correctly using a 32-bit and a 64-bit PHP system?

Question 2: When $num is read from a MySQL database using a standard FLOAT type (no precision specified) at the beginning of the loop and stored back at the end of the loop, is the answer to Question 1 still valid?

  • 写回答

1条回答 默认 最新

  • douba9020 2015-12-29 21:25
    关注

    PHP uses double precision floating point, which has a 52-bit mantissa. This means that integers represented using floats start losing precision when they reach 253 (the extra bit of precision is because the leading bit of a normalized mantissa is always 1, so this doesn't need to be included explicitly in the representation). The following example demonstrates this:

    echo number_format(pow(2.0, 53)-1) . "<br>" . 
         number_format(pow(2.0, 53)) . "<br>" .  
         number_format(pow(2.0, 53)+1);
    

    outputs:

    9,007,199,254,740,991
    9,007,199,254,740,992
    9,007,199,254,740,992 
    

    To get equivalent floating point precision in MySQL you should use the DOUBLE datatype, which is 64-bit floating point. If you just use FLOAT you'll get 32-bit single precision, which only has 23 bits of mantissa, and loses integer precision at 16,777,216.

    See FLOAT and DOUBLE Data Type Representation for more details about how MySQL stores floating point internally.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部