views:

2277

answers:

20

So in Ruby there is a trick to specify infinity:

1.0/0
=> Infinity

I believe in Python you can do something like this

float('inf')

These are just examples though, I'm sure most languages have infinity in some capacity. When would you actually use this construct in the real world? Why would using it in a range be better than just using a boolean expression? For instance

(0..1.0/0).include?(number) == (number >= 0) # True for all values of number
=> true

To summarise, what I'm looking for is a real world reason to use Infinity.

EDIT: I'm looking for real world code. It's all well and good to say this is when you "could" use it, when have people actually used it.

+15  A: 

Off the top of the head, it can be useful as an initial value when searching for a minimum value.

For example:

min = float('inf')

for x in somelist:
  if x<min: 
    min=x

Which I prefer to setting min initially to the first value of somelist

Of course, in Python, you should just use the min() built-in function in most cases.

Triptych
In .NET, for example, there are Min and Max values that are used more than infinity -- for example, Int32.MinValue.
Joel Marcey
**No**, because the minimum value of an empty list is not infinity but simply doesn't exist.
Dario
.NET also has System.Double.PositiveInfinity.
Jonas Elfström
@Dario: You can think about it as similar to the product of an empty set (`x^0 = 1`). Technically, max and min (or **join and meet**) each form a **monoid** with an **identity element** of the **least upper bound** /greatest lower bound respectively. Floating point numbers exist on the **extended real number line**, which has `+Inf`/`-Inf` as its LUB/GLB. (Wikipedia any bolded term for more!)
Porges
+1  A: 

When working in a problem domain where trig is used (especially tangent) infinity is an answer that can come up. Trig ends up being used heavily in graphics applications, games, and geospatial applications, plus the obvious math applications.

John Meagher
+8  A: 

In some physics calculations you can normalize irregularities (ie, infinite numbers) of the same order with each other, canceling them both and allowing a approximate result to come through.

When you deal with limits, calculations like (infinity / infinity) -> approaching a finite a number could be achieved. It's useful for the language to have to ability to overwrite the regular divide-by-zero error.

Eran Galperin
This really is the best real world example, in my opinion. Use an graphing calculator to "magically" calculate a limit and you will see it in action. +1
William Brendel
the crucial bit of course is that the infinities balance, this being a problem in several major research fields
annakata
Claim your NaNs at the counter. ;)
3yE
+1  A: 

I'm sure there are other ways to do this, but you could use Infinity to check for reasonable inputs in a String-to-Float conversion. In Java, at least, the Float.isNaN() static method will return false for numbers with infinite magnitude, indicating they are valid numbers, even though your program might want to classify them as invalid. Checking against the Float.POSITIVE_INFINITY and Float.NEGATIVE_INFINITY constants solves that problem. For example:

// Some sample values to test our code with
String stringValues[] = {
  "-999999999999999999999999999999999999999999999",
  "12345",
  "999999999999999999999999999999999999999999999"
};

// Loop through each string representation
for (String stringValue : stringValues) {
  // Convert the string representation to a Float representation
  Float floatValue = Float.parseFloat(stringValue);

  System.out.println("String representation: " + stringValue);
  System.out.println("Result of isNaN: " + floatValue.isNaN());

  // Check the result for positive infinity, negative infinity, and
  // "normal" float numbers (within the defined range for Float values).
  if (floatValue == Float.POSITIVE_INFINITY) {
    System.out.println("That number is too big.");
  } else if (floatValue == Float.NEGATIVE_INFINITY) {
    System.out.println("That number is too small.");
  } else {
    System.out.println("That number is jussssst right.");
  }
}

Sample Output:

String representation: -999999999999999999999999999999999999999999999
Result of isNaN: false
That number is too small.

String representation: 12345
Result of isNaN: false
That number is jussssst right.

String representation: 999999999999999999999999999999999999999999999
Result of isNaN: false
That number is too big.

William Brendel
+20  A: 

Dijkstra's Algorithm typically assigns infinity as the initial edge weights in a graph. This doesn't have to be "infinity", just some arbitrarily constant but in java I typically use Double.Infinity. I assume ruby could be used similarly.

Simucal
First thing that sprang to mind when I read this question.
madlep
The Bellman-ford algorithm solves similar problems as Dijkstra's and also uses infinity to denote inaccessibility.
vinc456
Double.Infinity? why stop there? Go for Triple.Infinitiy. :)
Doug T.
Yeah, pretty much any algorithm operating on weighted digraphs could reasonably involve infinity in some way (as the "weight" of a non-existent or unknown edge).
bcat
+4  A: 

Alpha-beta pruning

pantsgolem
A: 

Some programmers use Infinity or NaNs to show a variable has never been initialized or assigned in the program.

A: 

Good question - all the answers so far are contrived cases, and I can't think of anything.

Dustin Getz
I am not sure they are all contrived ... I mean if you have a MaxValue and a MinValue to a data type, you would probably use that, but there are cases where you want to start with the maximum number, especially in loops.
Joel Marcey
-1: How is this an answer? It's a comment on the question as a whole.
S.Lott
haha i don't really care
Dustin Getz
+1  A: 

I use it when I have a Range object where one or both ends need to be open

+6  A: 

Use Infinity and -Infinity when implementing a mathematical algorithm calls for it.

In Ruby, Infinity and -Infinity have nice comparative properties so that -Infinity < x < Infinity for any real number x. For example, Math.log(0) returns -Infinity, extending to 0 the property that x > y implies that Math.log(x) > Math.log(y). Also, Infinity * x is Infinity if x > 0, -Infinity if x < 0, and 'NaN' (not a number; that is, undefined) if x is 0.

For example, I use the following bit of code in part of the calculation of some log likelihood ratios. I explicitly reference -Infinity to define a value even if k is 0 or n AND x is 0 or 1.

Infinity = 1.0/0.0
def Similarity.log_l(k, n, x)
  unless x == 0 or x == 1
    k * Math.log(x.to_f) + (n-k) * Math.log(1.0-x)
  end
    -Infinity
  end
end
Bkkbrad
+11  A: 

There seems to be an implied "Why does this functionality even exist?" in your question. And the reason is that Ruby and Python are just giving access to the full range of values that one can specify in floating point form as specified by IEEE.

This page seems to describe it well: http://steve.hollasch.net/cgindex/coding/ieeefloat.html

As a result, you can also have NaN (Not-a-number) values and -0.0, while you may not immediately have real-world uses for those either.

InfiniteVoid
Good find on the summary! Just to clarify, I had read the IEEE specification before posting the question. I understand the theoretical usefulness of the construct, I was just curious as to how people had applied it as I have never come across it in code before.
Chris Lloyd
+1  A: 

I've used it in the minimax algorithm. When I'm generating new moves, if the min player wins on that node then the value of the node is -∞. Conversely, if the max player wins then the value of that node is +∞.

Also, if you're generating nodes/game states and then trying out several heuristics you can set all the node values to -∞/+∞ which ever makes sense and then when you're running a heuristic its easy to set the node value:

node_val = -∞
node_val = max(heuristic1(node), node_val)
node_val = max(heuristic2(node), node_val)
node_val = max(heuristic2(node), node_val)
Lolindrath
+1  A: 

I've used it in a DSL similar to Rails' has_one and has_many:

has 0..1 :author
has 0..INFINITY :tags

This makes it easy to express concepts like Kleene star and plus in your DSL.

James A. Rosen
+6  A: 

I use it to specify the mass and inertia of a static object in physics simulations. Static objects are essentially unaffected by gravity and other simulation forces.

Nick
+2  A: 

I've used it for cases where you want to define ranges of preferences / allowed.

For example in 37signals apps you have like a limit to project number

Infinity = 1 / 0.0
FREE = 0..1
BASIC = 0..5
PREMIUM = 0..Infinity

then you can do checks like

if PREMIUM.include? current_user.projects.count 
 # do something
end
ucron
A: 

I've used symbolic values for positive and negative infinity in dealing with range comparisons to eliminate corner cases that would otherwise require special handling:

Given two ranges A=[a,b) and C=[c,d) do they intersect, is one greater than the other, or does one contain the other?

A > C iff a >= d
A < C iff b <= c
etc...

If you have values for positive and negative infinity that respectively compare greater than and less than all other values, you don't need to do any special handling for open-ended ranges. Since floats and doubles already implement these values, you might as well use them instead of trying to find the largest/smallest values on your platform. With integers, it's more difficult to use "infinity" since it's not supported by hardware.

Eclipse
A: 

It is used quite extensively in graphics. For example, any pixel in a 3D image that is not part of an actual object is marked as infinitely far away. So that it can later be replaced with a background image.

+1  A: 

I used it for representing camera focus distance and to my surprise in Python:

>>> float("inf") is float("inf")
False
>>> float("inf") == float("inf")
True

I wonder why is that.

dhill
Well huh... that's odd. Trying it out myself, I also found that if you assign `float('inf')` to a variable (say, `a`) and then try `a is a`, it does return `True`. Then, doing `b = 0`, then `b += a`, `a is b` will return `False` and `a == b` returns `True`. In other words, using `is` checks if the floats are the same object, while using `==` checks if they have the same value.
JAB
Apparently is is just an equality on `id` and the implementation doesn't use the tricks here, as it does on integers. Infinity is used rather rarely as the question suggests. Now I wonder, why I wondered then ;P
dhill
+1  A: 

In Ruby infinity can be used to implement lazy lists. Say i want N numbers starting at 200 which get successively larger by 100 units each time:

Inf = 1.0 / 0.0
(200..Inf).step(100).take(N)

More info here: http://banisterfiend.wordpress.com/2009/10/02/wtf-infinite-ranges-in-ruby/

banister
A: 

I ran across this because I'm looking for an "infinite" value to set for a maximum, if a given value doesn't exist, in an attempt to create a binary tree. (Because I'm selecting based on a range of values, and not just a single value, I quickly realized that even a hash won't work in my situation.)

Since I expect all numbers involved to be positive, the minimum is easy: 0. Since I don't know what to expect for a maximum, though, I would like the upper bound to be Infinity of some sort. This way, I won't have to figure out what "maximum" I should compare things to.

Since this is a project I'm working on at work, it's technically a "Real world problem". It may be kindof rare, but like a lot of abstractions, it's convenient when you need it!

Also, to those who say that this (and other examples) are contrived, I would point out that all abstractions are somewhat contrived; that doesn't mean they are useful when you contrive them.

alpheus