来自 microtime 的圆形浮点数

发布于 2024-12-27 21:32:48 字数 449 浏览 3 评论 0原文

PHP 版本 5.3.6

示例

<?php
$timeStart = microtime(true);
// some code ...    
$timeExecution = microtime(true) - $timeStart;
$time = round($timeExecution, 2);
file_put_contents('h:/round.txt', $timeExecution . ' = ' . $time . "\n", FILE_APPEND);
?>

文件 round.txt 包含以下行:

131.3048491477966 = 131.3

8.340715885162354 = 8.34

8.198318004608154 = 8.199999999999999

这怎么可能?

PHP Version 5.3.6

Example

<?php
$timeStart = microtime(true);
// some code ...    
$timeExecution = microtime(true) - $timeStart;
$time = round($timeExecution, 2);
file_put_contents('h:/round.txt', $timeExecution . ' = ' . $time . "\n", FILE_APPEND);
?>

File round.txt contains these lines:

131.3048491477966 = 131.3

8.340715885162354 = 8.34

8.198318004608154 = 8.199999999999999

how is that possible?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

多情癖 2025-01-03 21:32:48

http://php.net/manual/en/language.types.float.php

此外,可以精确表示为以 10 为基数的浮点数的有理数(例如 0.1 或 0.7),不能精确表示为以 2 为基数的浮点数(在内部使用),无论尾数的大小如何。因此,它们无法在不损失少量精度的情况下转换为内部二进制对应项。这可能会导致令人困惑的结果:例如,floor((0.1+0.7)*10) 通常会返回 7 而不是预期的 8,因为内部表示将类似于 7.9999999999999991118....

http://php.net/manual/en/language.types.float.php

Additionally, rational numbers that are exactly representable as floating point numbers in base 10, like 0.1 or 0.7, do not have an exact representation as floating point numbers in base 2, which is used internally, no matter the size of the mantissa. Hence, they cannot be converted into their internal binary counterparts without a small loss 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, since the internal representation will be something like 7.9999999999999991118....

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文