开发者

Checking that float modulo int is finite ordinal

开发者 https://www.devze.com 2023-03-10 05:27 出处:网络
In a for-loop, I\'m integrating with respect to time with constant, fractional time step, dt. I only want to save the simulation results for integral (finite ordinal) time points. My solution is as fo

In a for-loop, I'm integrating with respect to time with constant, fractional time step, dt. I only want to save the simulation results for integral (finite ordinal) time points. My solution is as follows,

dt = 0.1
steps = 100

for step in range(steps):
    if (step*dt) % 1 == 0.0:
        print step

I've never really trusted modular arithmetic on floats. Is there a better w开发者_如何学Pythonay to check if a float is integral or am I simply being paranoid?


This is dangerous, in any programming language. In your example, 0.1 cannot be represented exactly by in floating-point, so that test will never pass (well I suppose it may do after 2^24 iterations or so). In many cases, the step size may not have an exact representation in floating-point, so that the accumulated rounding error causes the test to erroneously trigger/not trigger. In other cases, as the accumulated value gets larger, eventually it will begin to lose precision due to the increasing exponent (in your example, assuming Python uses single-precision by default, you'll get an erroneous trigger after 20971529 iterations).

Try to find a way to avoid performing equality tests on floating-point values (checking for integral values is one such test). So in your case, just test on step % 10.


I don't trust floats either, you can use the Decimal type or, you can use types. I like types better.

0

精彩评论

暂无评论...
验证码 换一张
取 消