In what contexts do programming languages make real use of an Infinity value?

旧巷老猫 提交于 2021-02-04 10:17: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 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.


回答1:


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.




回答2:


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.




回答3:


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.




回答4:


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.




回答5:


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



回答6:


Alpha-beta pruning




回答7:


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.




回答8:


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/




回答9:


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



回答10:


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.




回答11:


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)



回答12:


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.




回答13:


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




回答14:


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.




回答15:


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.




回答16:


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.




回答17:


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.




回答18:


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.




回答19:


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".




回答20:


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




回答21:


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))



回答22:


For sorting

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




回答23:


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.




回答24:


You can to use:

import decimal
decimal.Decimal("Infinity")

or:

from decimal import *
Decimal("Infinity")


来源:https://stackoverflow.com/questions/382603/in-what-contexts-do-programming-languages-make-real-use-of-an-infinity-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!