如何使用FMOD,避免precision问题 [英] How to use fmod and avoid precision issues
问题描述
我要归结这个问题最简单的形式:
让的从[0 .. 5.0]进行迭代以0.05的步骤,并打印出X
每0.25乘数。
块引用>的(双D = 0.0; D< = 5.0; D + = 0.05){
如果(FMOD(四,0.25)等于0)
打印'X';
}这当然不会,因为
D
将[0,0.05000000001,0.100000000002 ...]造成的 FMOD()的失败合作。极端的例子是,当D = 1.999999999998
和FMOD(D,0.25)= 1
。如何解决呢? 这里是可编辑的在线例子。
解决方案我想通过简单地以这种方式不使用浮点变量解决这个问题
的for(int i = 0; I< = 500; I + = 5){
双D = 1 / 100.0; //如果你需要使用它。
如果((我25%)== 0)
打印'X';
}他们通常有问题,以至于它值得一点点额外的努力避免它们。
I'm going to boil this problem down to the simplest form:
Let's iterate from [0 .. 5.0] with a step of 0.05 and print out 'X' for every 0.25 multiplier.
for(double d=0.0; d<=5.0; d+=0.05) { if(fmod(d,0.25) is equal 0) print 'X'; }
This will of course not work since
d
will be [0, 0.05000000001, 0.100000000002, ...] causing fmod() to fail. Extreme example is whend=1.999999999998
andfmod(d,0.25) = 1
.How to tackle this? Here is an editable online example.
解决方案I'd solve this by simply not using floating point variables in that way:
for (int i = 0; i <= 500; i += 5) { double d = i / 100.0; // in case you need to use it. if ((i % 25) == 0) print 'X'; }
They're usually problematic enough that it's worth a little extra effort in avoiding them.
这篇关于如何使用FMOD,避免precision问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!