Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is Float::INFINITY == Float::INFINITY in Ruby?

Tags:

math

ruby

In mathematics 2 infinities are not equal, nor greater than or less then. So what gives?

In irb, Float::INFINITY == Float::INFINITY (tested in ruby 1.9.3)

like image 324
Archit Baweja Avatar asked Jan 10 '13 01:01

Archit Baweja


People also ask

What is infinity in Ruby?

What is infinity in Ruby? It's something that has a starting point but no ending. In Ruby, we can express this concept of infinity with the Float::INFINITY constant.

What is float in Ruby?

A floating-point number or a float represents a real number. Real numbers can be either a rational or an irrational number; numbers that contain a fractional part, such as 9.0 or -116.42 . In other words, a float in a Ruby program is a number that contains a decimal point.

How do you make a float in Ruby?

The to_f function in Ruby converts the value of the number as a float. If it does not fit in float, then it returns infinity. Parameter: The function takes the integer which is to be converted to float.

Does Ruby have double?

In Ruby, the double at-sign ( @@ ) before a variable name (e.g. @@variable_name ) is used to create a class variable.


1 Answers

In more technical terms, it all comes down to the IEEE 754 standard for floating-point arithmetics.

The IEEE 754 standard does implicitly define Infinity == Infinity to be true. The relevant part of the standard is section 5.7: "Four mutually exclusive relations are possible [between two IEEE 754 values]: less than, equal, greater than, and unordered. The last case arises when at least one operand is NaN."

Between any pair of floating point values exactly one of these four relations is true. Therefore, since Infinity is not NaN, Infinity is not unordered with respect to itself. Having one of (Infinity < Infinity) and (Infinity > Infinity) be true wouldn't be consistent, so (Infinity == Infinity).

This was taken from http://compilers.iecc.com/comparch/article/98-07-134

like image 121
brain Avatar answered Oct 06 '22 04:10

brain