Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why in Ruby 0.0/0, 3.0/0 and 3/0 behave differently?

If I divide by 0, I get either a ZeroDivisionError, Infinity or NaN depending on what is divided.

ruby-1.9.2-p180 :018 > 0.0 / 0
 => NaN 

ruby-1.9.2-p180 :020 > 3.0 / 0
 => Infinity 

ruby-1.9.2-p180 :021 > 3 / 0
ZeroDivisionError: divided by 0

I understand that 0.0 / 0 is not an Infinity (in math terms), while 3.0 / 0 is but why then isn't 3 / 0 an Infinity? Why dividing an integer throws an exception but dividing a float doesn't?

like image 301
Evgeny Shadchnev Avatar asked Dec 16 '22 08:12

Evgeny Shadchnev


1 Answers

In Ruby, not all numbers are created equal (pun intended).

Decimal numbers (0.0, 3.0) follow the IEEE 754-2008 standard for floating point arithmetic:

The standard defines arithmetic formats: sets of binary and decimal floating-point data, which consist of finite numbers (including signed zeros and subnormal numbers), infinities, and special "not a number" values (NaNs)

Whole numbers (0, 3) are treated as integers.

Both NaN and Infinity (as well as -Infinity) are special cases that such floats are designed to handle, but integers are not -- hence the error.

like image 120
namuol Avatar answered Jan 01 '23 07:01

namuol