28

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 summarize, 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.

einpoklum
  • 118,144
  • 57
  • 340
  • 684
Chris Lloyd
  • 12,100
  • 7
  • 36
  • 32

24 Answers24

35

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.

Kenan Banks
  • 207,056
  • 34
  • 155
  • 173
  • In .NET, for example, there are Min and Max values that are used more than infinity -- for example, Int32.MinValue. – Joel Marcey Dec 20 '08 at 00:33
  • 8
    **No**, because the minimum value of an empty list is not infinity but simply doesn't exist. – Dario Jan 26 '10 at 19:12
  • .NET also has System.Double.PositiveInfinity. – Jonas Elfström Jan 26 '10 at 19:22
  • 9
    @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 Apr 13 '10 at 20:34
  • 4
    @Dario: As Porges says, the minimum of an empty list *is* arguably infinity, just as the [sum of an empty list is 0](http://en.wikipedia.org/wiki/Empty_sum) and [the product of an empty list](http://en.wikipedia.org/wiki/Empty_product) is 1, and so on. (This is because infinity is the identity for "minimum", just as 0 is the identity for addition and 1 is the identity for multiplication.) – ShreevatsaR Dec 03 '10 at 16:58
  • That's how I just used it, just now. An example of when you might not be able to use `min`: when the values you're taking the minimum of aren't available all at once, and you want the running minimum. (Maybe each new value takes a long time to compute, or is being sent to you over the network.) – Kragen Javier Sitaker Dec 29 '11 at 16:58
  • Y'all are thinking of it in high-faultin' mathematical sense, but all I see is a convenient way to make sure any number will be less than the initial value of `min`... – Schilcote Feb 17 '14 at 15:25
35

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.

mmcdole
  • 91,488
  • 60
  • 186
  • 222
  • 1
    The Bellman-ford algorithm solves similar problems as Dijkstra's and also uses infinity to denote inaccessibility. – vinc456 Jan 13 '09 at 14:55
  • 19
    Double.Infinity? why stop there? Go for Triple.Infinitiy. :) – Doug T. Dec 11 '09 at 03:12
  • 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 Dec 11 '09 at 03:13
  • 2
    This BTW, is a special case of @Triptych's answer: infinity is the minimum of an empty list. (Dijkstra's algorithm or Bellman-Ford algorithm work by setting weights and repeatedly setting them to the minimum of their current value and some other value.) – ShreevatsaR Dec 03 '10 at 16:59
17

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
  • 171
  • 2
  • 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 Dec 20 '08 at 23:01
11

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 the ability to overwrite the regular divide-by-zero error.

Eran Galperin
  • 86,251
  • 24
  • 115
  • 132
10

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
  • 3,087
  • 24
  • 30
8

Alpha-beta pruning

pantsgolem
  • 2,350
  • 1
  • 16
  • 7
8

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 Van Brunt
  • 15,244
  • 11
  • 66
  • 92
6

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/

horseyguy
  • 29,455
  • 20
  • 103
  • 145
5

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
Michael Myers
  • 188,989
  • 46
  • 291
  • 292
ucron
  • 2,822
  • 2
  • 18
  • 6
  • I really like this because you're expressing your actual intent. `Infinity` represents the unbounded, just like `nil` represents the unknown. – Nathan Long Aug 22 '14 at 14:00
4

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
  • 3,327
  • 2
  • 19
  • 18
  • 1
    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 Jul 31 '09 at 18:18
  • 2
    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 Aug 06 '09 at 12:31
  • 2
    you should pretty much never use "is" in python as it bypasses the programmable "==" functionality. "is" gives insight to how the python runtime is implemented, but in my experience is more trouble than it's worth, so I always use "==". – thejoshwolfe Sep 17 '11 at 21:14
  • 3
    `a is b` in Python tells you whether modifying `a` will make the same modification to `b`. For immutable objects such as floats, that question disappears. – Kragen Javier Sitaker Dec 29 '11 at 17:01
3

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
  • 2,101
  • 14
  • 20
3

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
  • 64,193
  • 61
  • 179
  • 261
2

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
  • 1
  • 1
2

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

2

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
  • 44,851
  • 20
  • 112
  • 171
1

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
  • 22,808
  • 14
  • 54
  • 57
1

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
  • 31,712
  • 14
  • 72
  • 77
1

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.

Megamug
  • 6,277
  • 5
  • 21
  • 13
  • This is another example of the "minimum of a set" answer, but it makes it really clear why it doesn't always make sense to just call `min()` with the set as an argument :) – Kragen Javier Sitaker Dec 29 '11 at 17:06
1

I'm using a network library where you can specify the maximum number of reconnection attempts. Since I want mine to reconnect forever:

my_connection = ConnectionLibrary(max_connection_attempts = float('inf'))

In my opinion, it's more clear than the typical "set to -1 to retry forever" style, since it's literally saying "retry until the number of connection attempts is greater than infinity".

Brendan Long
  • 53,280
  • 21
  • 146
  • 188
0

If you want the largest number from an input but they might use very large negatives. If I enter -13543124321.431 it still works out as the largest number since it's bigger than -inf.

enter code here
initial_value = float('-inf')
while True:
    try:
        x = input('gimmee a number or type the word, stop ')
    except KeyboardInterrupt:
        print("we done - by yo command")
        break
    if x == "stop":
        print("we done")
        break
    try:
        x = float(x)
    except ValueError:
        print('not a number')
        continue
    if x > initial_value: initial_value = x
print("The largest number is: " + str(initial_value))
cybervigilante
  • 231
  • 1
  • 5
0

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

James A. Rosen
  • 64,193
  • 61
  • 179
  • 261
-1

For sorting

I've seen it used as a sort value, to say "always sort these items to the bottom".

Nathan Long
  • 122,748
  • 97
  • 336
  • 451
-1

To specify a non-existent maximum

If you're dealing with numbers, nil represents an unknown quantity, and should be preferred to 0 for that case. Similarly, Infinity represents an unbounded quantity, and should be preferred to (arbitrarily_large_number) in that case.

I think it can make the code cleaner. For example, I'm using Float::INFINITY in a Ruby gem for exactly that: the user can specify a maximum string length for a message, or they can specify :all. In that case, I represent the maximum length as Float::INFINITY, so that later when I check "is this message longer than the maximum length?" the answer will always be false, without needing a special case.

Nathan Long
  • 122,748
  • 97
  • 336
  • 451
-1

You can to use:

import decimal
decimal.Decimal("Infinity")

or:

from decimal import *
Decimal("Infinity")
Andrew Grimm
  • 78,473
  • 57
  • 200
  • 338
  • This doesn't answer the actual question originally posed of "what I'm looking for is a real world reason to use Infinity." – zzzirk Nov 07 '12 at 13:49