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

Why does 4.1% 2 return 0.0999999999999996? But 4.2% 2 == 0.2.

+5
source share
5 answers

See here: What Every Programmer Should Know About Floating-Point Arithmetic

Real numbers are endless. Computers work with a finite number of bits (32 bits, 64 bits today). As a result, floating point arithmetic performed by computers cannot represent all real numbers. 0.1 is one of these numbers.

Note that this is not a problem with Ruby, but with all programming languages, because it comes from the way computers represent real numbers.

+5
source

Float , .

+1

, 4.1 = 4.0999999999999996447286321199499070644378662109375 4.2 = 4.20000000000000017763568394002504646778106689453125. , 4.1 , , 4.2 .

0.20000000000000017... 0,2, 0.099999999999999644... 0,1? Ruby, , 15 .

+1

Because you work with a floating point. A floating point binary cannot exactly represent 0.1.

0
source

All Articles