Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 907
Alex Avatar asked Jan 09 '12 12:01

Alex


1 Answers

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.

like image 167
Manuel Selva Avatar answered Nov 15 '22 08:11

Manuel Selva