Home  >  Article  >  Backend Development  >  两个FLOAT相加出现的奇怪现象~解决思路

两个FLOAT相加出现的奇怪现象~解决思路

WBOY
WBOYOriginal
2016-06-13 13:47:581881browse

两个FLOAT相加出现的奇怪现象~~~~

PHP code
<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

-->
list ( $usec, $sec ) = explode ( ' ', microtime () );

printf("秒:%.16f", (float)$sec);
printf("微秒:%.16f", (float)$usec);
printf("相加:%.16f", ( float ) $usec + ( float ) $sec);


输出结果是:
秒:1327048300.0000000000000000
微秒:0.9687510000000000
相加:1327048300.9687509536743164 

我知道浮点数是一个近似值,但是我现在打印$usec且保留小数点后16位的时候,它就是没有小数啊?那不就可以认为它就等于1327048300吗?
它两个相加为什么不是1327048300.9687510000000000呢??

谢谢!!

------解决方案--------------------
Warning
浮点数精度
显然简单的十进制分数如同 0.1 或 0.7 不能在不丢失一点点精度的情况下转换为内部二进制的格式。这就会造成混乱的结果:例如,floor((0.1+0.7)*10) 通常会返回 7 而不是预期中的 8,因为该结果内部的表示其实是类似 7.9999999999...。
这和一个事实有关,那就是不可能精确的用有限位数表达某些十进制分数。例如,十进制的 1/3 变成了 0.3333333. . .。

所以永远不要相信浮点数结果精确到了最后一位,也永远不要比较两个浮点数是否相等。如果确实需要更高的精度,应该使用任意精度数学函数或者 gmp 函数
------解决方案--------------------
连什么是有效数都弄不清楚,真不明白你们爹妈花许多钱供你们上大学是为什么
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn