Use modulo operation to get more precise msec #2572
Merged
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
1. 整型转换为浮点型可能会导致误差
首先在 C 中,32 位的单精度浮点数表示如下
更多关于浮点数的格式,请参考 IEEE_754
当将整数转换为浮点数时,由于浮点数的
Rounding
,在某些情况下会导致结果有些不同。对于 32 位的单精度浮点数,当整数
n > 2 ^ 24
时,就有可能发生Rounding
。考虑如下程序编译程序运行得到如下结果
有的值被 round-up,而有的值被 round-down
2. 浮点数的四则运算也可能会导致误差
同样的,浮点数在四则运算中也会发生
Rounding
.编译程序运行得到如下结果
总结
模运算更便宜,也不会因为浮点数的
Rounding
而产生误差。所以推荐使用摸运算参考文献: