fmod函数返回错误的结果 [英] fmod function returning wrong result
问题描述
for($ i = 0.00; $ i <1; $ i = $ i + 0.05){
不是零,而是表示适当整数与
var_dump($ i。=.fmod($ i,0.05));
$ b $ p $输出:
0. = 0
0.05 = 0
0.1 = 0
0.15 = 1.3877787807814E-17
0.2 = 0
0.25 = 0.05
0.3 = 0.05
0.35 = 0.05
0.4 = 0.05
0.45 = 0.05
0.5 = 0.05
0.55 = 0.05
0.6 = 0.05
0.65 = 0.05
0.7 = 2.7755575615629E-17
0.75 = 6.9388939039072E-17
0.8 = 1.1102230246252E-16
0.85 = 1.5265566588596E-16
0.9 = 1.942890293094E-16
0.95 = 2.3592239273285E-16
首先,
是确切的。因为它可以:当fmod
每个结果都是相同的:x
和y
是浮点数时,第二,当你写
地区不准确,因为在二进制中, 0.05有很多数字。随着总和变大,最后的数字逐渐被丢弃。这就是时,可以将其作为一个浮点数来表示。 0.05
,你不能得到正确的数字,因为另一方面5/100不能完全表示为浮点数;当你写+
时,你一般不会得到数学加法,因为数学加法的结果不能总是用浮点数(*)来表示。 p>
从0.0开始,反复添加0.05会很快导致您的
+ +
的不准确之处,最终导致fmod
不能给出结果。
如果将
0.05
并不完全是5/100是确切的。但是由于浮点数0.05
在二进制中有许多数字(而不是十进制),并且由于在计算0.05
,当计算<$时,您获得的最大倍数y
的值为0.05
c $ c> fmod(y,0.05)0.05
的数学乘积与近似值y
。
(*)当数学和可以表示时,数学和就是你得到,但有时却不行。I'm getting fmod returning wrong result, am i doing anything wrong?
for($i = 0.00; $i < 1; $i = $i + 0.05) { var_dump($i." = ".fmod($i, 0.05)); }
Output:
0.= 0 0.05 = 0 0.1 = 0 0.15 = 1.3877787807814E-17 0.2 = 0 0.25 = 0.05 0.3 = 0.05 0.35 = 0.05 0.4 = 0.05 0.45 = 0.05 0.5 = 0.05 0.55 = 0.05 0.6 = 0.05 0.65 = 0.05 0.7 = 2.7755575615629E-17 0.75 = 6.9388939039072E-17 0.8 = 1.1102230246252E-16 0.85 = 1.5265566588596E-16 0.9 = 1.942890293094E-16 0.95 = 2.3592239273285E-16
I was expecting every result to be the same: 0.
解决方案First,
fmod
is exact. Because it can: whenx
andy
are floating-point numbers, the mathematical result offmod(x,y)
can be represented exactly as a floating-point number.Second, when you write
0.05
, you do not get exactly that number, because 5/100 on the other hand cannot be represented exactly as a floating-point number; and when you write+
, you do not get mathematical addition in general because the result of that mathematical addition cannot always be represented as a floating-point number(*).Starting from 0.0 and repeatedly adding 0.05 will soon get you into inaccurate
+
territory, because in binary, the best representation of 0.05 has many digits. As the sum gets larger, the last digits progressively have to be dropped. This is where the inaccuracy of+
comes from, and ultimately is the reason whyfmod
does not give you the results you expect.It wouldn't matter that
0.05
is not exactly 5/100 if repeatedly adding it to zero always was exact. But since the floating-point number0.05
has many digits in binary (as opposed to decimal) and since some of these digits must be lost when computing multiples of0.05
, the value you get for most multiplesy
of0.05
when computingfmod(y, 0.05)
is not zero but represents the difference between the mathematical multiplication of the appropriate integer by0.05
and the approximationy
of that number.(*) when the mathematical sum can be represented, the mathematical sum is what you get, but sometimes it just cannot.
这篇关于fmod函数返回错误的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!