Alex
Alex

Reputation: 307

Why 4.1%2 returns 0.0999999999999996 using Ruby?But 4.2%2==0.2

Why 4.1%2 returns 0.0999999999999996?But 4.2%2==0.2.

Upvotes: 5

Views: 292

Answers (5)

Rick Regan
Rick Regan

Reputation: 3512

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.

Upvotes: 1

Ned Batchelder
Ned Batchelder

Reputation: 375644

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.

Upvotes: 1

Manuel Selva
Manuel Selva

Reputation: 19050

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.

Upvotes: 5

Michael Kohl
Michael Kohl

Reputation: 66837

Floats can not always be represented exactly, see

What Every Programmer Should Know About Floating-Point Arithmetic

Upvotes: 1

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272557

Because you're working in floating-point. Binary floating-point cannot represent 0.1 exactly.

Upvotes: 0

Related Questions