问题
Why 4.1%2 returns 0.0999999999999996?But 4.2%2==0.2.
回答1:
See here: What Every Programmer Should Know About Floating-Point Arithmetic
Real numbers are infinite. Computers are working with a finite number of bits (32 bits, 64 bits today). As a result floating-point arithmetic done by computers cannot represent all the real numbers. 0.1 is one of these numbers.
Note that is not an issue related to Ruby, but to all programming languages because it comes from the way computers represent real numbers.
回答2:
Float
s can not always be represented exactly, see
What Every Programmer Should Know About Floating-Point Arithmetic
回答3:
Here's a different page about floating-point: http://docs.python.org/tutorial/floatingpoint.html. It's from the Python docs, but it's true of all languages that use fixed-size binary floats.
回答4:
In double-precision, 4.1 = 4.0999999999999996447286321199499070644378662109375 and 4.2 = 4.20000000000000017763568394002504646778106689453125. In other words, the binary approximation to decimal 4.1 is slightly less than you'd expect, and the binary approximation to decimal 4.2 is slightly more.
Now why did 0.20000000000000017... round to 0.2 but 0.099999999999999644... NOT round to 0.1? Ruby is probably rounding all output to 15 significant decimal digits.
回答5:
Because you're working in floating-point. Binary floating-point cannot represent 0.1 exactly.
来源:https://stackoverflow.com/questions/8788640/why-4-12-returns-0-0999999999999996-using-rubybut-4-22-0-2