Minus infinity in python

How can I represent an infinite number in Python?

How can I represent an infinite number in python? No matter which number you enter in the program, no number should be greater than this representation of infinity.

math.inf is useful as an initial value in optimisation problems, because it works correctly with min, eg. min(5, math.inf) == 5 . For example, in shortest path algorithms, you can set unknown distances to math.inf without needing to special case None or assume an upper bound 9999999 . Similarly, you can use -math.inf as a starting value for maximisation problems.

In most cases, an alternative to using math.inf in optimization problems is to start with the first value.

Can’t help but wonder how so many Python question seems to attract a multitude of ways to do the same thing. How is that Pythonian or compatible with Zen of Python.

@nyholku It looks to me like the answers here are all substantively suggesting doing the same thing, though. Floating-point infinity is the same built-in object whether you access it as a constant in the math standard library or by asking the float type to parse the string «inf» .

13 Answers 13

import math test = math.inf 
test > 1 test > 10000 test > x 

Will always be true. Unless of course, as pointed out, x is also infinity or «nan» («not a number»).

Читайте также:  Заголовок

Additionally (Python 2.x ONLY), in a comparison to Ellipsis , float(inf) is lesser, e.g:

Note that infinity is defined in the norm IEEE 754-1985 (en.wikipedia.org/wiki/IEEE_754-1985), which Any modern language will rely on. Another point is that, according to this norm, infinity must (obviously) be a floating-point number. This might explain why Python have chosen this akward syntax.

Since Python 3.5 you can use math.inf :

No one seems to have mentioned about the negative infinity explicitly, so I think I should add it.

For positive infinity (just for the sake of completeness):

I don’t know exactly what you are doing, but float(«inf») gives you a float Infinity, which is greater than any other number.

There is an infinity in the NumPy library: from numpy import inf . To get negative infinity one can simply write -inf .

The first two are native i.e. require no dependency. np.inf requires the Numpy package. float(‘inf’) is a bit hacky as it involves parsing a string, but on the upside it does not even require an import and the parsing is typically computationally negligible. If you use one of the math packages anyway, though, then just use them. If you happen to use both math and np , then np.inf is the shortest one.

Another, less convenient, way to do it is to use Decimal class:

from decimal import Decimal pos_inf = Decimal('Infinity') neg_inf = Decimal('-Infinity') 

float(‘inf’) is float(‘inf’) -> False , just holds that they are different objects with different instances, but not that the internal contents are different — actually as @nemesisdesign pointed float(‘int’) == float(‘int’) holds to True . This is the same problem like comparing mutable objects like [1,2,3] is [1,2,3] and [1,2,3] == [1,2,3], which are, in order, False and True.. More info see: stackoverflow.com/questions/2988017/…

In python2.x there was a dirty hack that served this purpose (NEVER use it unless absolutely necessary):

It has been reasonably deprecated in python3. Now such comparisons end up with

TypeError: unorderable types: str() < int() 

If you really have yo use this, at least wrap it in some readable names like: MIN_INFINITY = None; INFINITY = "inf"; MIN_INFINITY < x < INFINITY

Also if you use SymPy you can use sympy.oo

>>> from sympy import oo >>> oo + 1 oo >>> oo - oo nan 

Infinity

1. Using float('inf') and float('-inf)

positive_infinity = float('inf') negative_infinity = float('-inf') 

2. Using Python’s math module

import math positive_infinity = math.inf negative_infinity = -math.inf 

3. Integer maxsize

import sys maxSize = sys.maxsize minSize = -sys.maxsize 

4. Using Python’s decimal module

from decimal import Decimal positive_infinity = Decimal('Infinity') negative_infinity = Decimal('-Infinity') 

5. Using Numpy Library

from numpy import inf positive_infinity = inf negative_infinity = -inf 
pos_inf_val = float("infinity") 
neg_inf_val = float("-infinity") 

Representing in python

float("inf") or float("INF") or float("Inf") or float("inF") or float("infinity") or float("Infinity") creates a float object holding

You can also represent -∞ in python

float("-inf") or float("-INF") or float("-Inf") or float("-infinity") creates a float object holding -∞

You can perform arithmetic operations:

infinity = float("inf") ninfinity = float("-inf") nan = float("nan") print(infinity*infinity)#inf print(ninfinity+infinity)#not a number print(1/-infinity)#is -0.0 print(nan*nan)# is not a number print(1/infinity) # is 0.0 since 1/∞ is 0 

Output:

$ python3 floating.py inf nan -0.0 nan 0.0 

Источник

How to implement negative infinity in python?

The below code shows the use of isinf() method: Python3 Output: Comparing infinite values to finite values in python The concept of comparing an infinite value to finite values is as simple as it gets. It is used as Decimal(‘Infinity’) for positive and Decimal(‘-Infinity’) for negative infinite value.

How to implement negative infinity in python?

I am trying to implement a Heap defined Priority Queue, the algorithm is from CLRS book chapter 6. The pseudocode is listed below:

Max_Heap_Insert(A, key): A.heap_size = A.heap_size + 1 A[A.heap_size] = -∞ Heap_Increase_Key(A, A.heap_size, key) 

My question is that using python, how do I define -∞?

Python has special values float('inf') and float('-inf') .

As it happens, in Python 2, None is less than any integer, so you can use None . In Python 3 you have (at least) four choices:

  1. Use min(A) - 1.
  2. Use None , and whenever you compare two values, explicitly test for them being None .
  3. Define a new data type that consists of either an integer or -∞, and handles comparisons correctly.
  4. Modify the algorithm so that line 2 is eliminated. You will have to patch Heap-Increase-Key somehow.

I stumbled across this while working on a heap implementation myself. 🙂

As of Python 3.5, you can use the inf constant from the math module

from math import inf inf + inf # inf inf - inf # nan inf / inf # nan inf * inf # inf max(list(range(1_000_000)) + [inf]) # inf min(list(range(-1_000_000, 1)) + [-inf]) # -inf 

I did not know this and used a custom class to achieve the same ordering property

class MinusInf: def __gt__(self, other): return False def __ge__(self): return False def __lt__(self, other): return True def __le__(self, other): return True def __eq__(self, other): return False minus_inf = MinusInf() minus_inf >= -1_000_000 # False 

This will work for the purpose of a heap, but the recommended way is to just use math.inf (or numpy.inf which is the inf constant from numpy).

Python Variables, If you want to specify the data type of a variable, this can be done with casting. Example x = str(3) # x will be '3' y = int(3) # y will be 3 z = float(3) # z will be 3.0 Try it Yourself » Get the Type You can get the data type of a variable with the type () function. Example x = 5 y = "John" print(type(x)) print(type(y)) Try it Yourself »

Python infinity

As ironic as it may seem Infinity is defined as an undefined number that can either be a positive or negative value. All arithmetic operations performed on an infinite value always lead to an infinite number, say it be sum, subtraction, multiplication, or any other operation.
In the world of computer science, infinity is generally used to measure performance and optimize algorithms that perform computations on a large scale application.

Representing infinity as an Integer in python
The concept of Representing infinity as an integer violates the definition of infinity itself. As of 2020, there is no such way to represent infinity as an integer in any programming language so far. But in python, as it is a dynamic language, float values can be used to represent an infinite integer. One can use float(‘inf’) as an integer to represent it as infinity. Below is the list of ways one can represent infinity in python.

1. Using float(‘inf’) and float(‘-inf’):

As infinity can be both positive and negative they can be represented as a float(‘inf’) and float(‘-inf’) respectively. The below code shows the implementation of the above-discussed content:

Источник

How to implement negative infinity in python?

I am trying to implement a Heap defined Priority Queue, the algorithm is from CLRS book chapter 6. The pseudocode is listed below:

Max_Heap_Insert(A, key): A.heap_size = A.heap_size + 1 A[A.heap_size] = -∞ Heap_Increase_Key(A, A.heap_size, key) 

4 Answers 4

Python has special values float('inf') and float('-inf') .

I prefer using the inf constant from the math module ( from math import inf ). You can then specify -inf for negative infinity.

As it happens, in Python 2, None is less than any integer, so you can use None . In Python 3 you have (at least) four choices:

  1. Use min(A) - 1.
  2. Use None , and whenever you compare two values, explicitly test for them being None .
  3. Define a new data type that consists of either an integer or -∞, and handles comparisons correctly.
  4. Modify the algorithm so that line 2 is eliminated. You will have to patch Heap-Increase-Key somehow.

I stumbled across this while working on a heap implementation myself. 🙂

As of Python 3.5, you can use the inf constant from the math module

from math import inf inf + inf # inf inf - inf # nan inf / inf # nan inf * inf # inf max(list(range(1_000_000)) + [inf]) # inf min(list(range(-1_000_000, 1)) + [-inf]) # -inf 

I did not know this and used a custom class to achieve the same ordering property

class MinusInf: def __gt__(self, other): return False def __ge__(self): return False def __lt__(self, other): return True def __le__(self, other): return True def __eq__(self, other): return False minus_inf = MinusInf() minus_inf >= -1_000_000 # False 

This will work for the purpose of a heap, but the recommended way is to just use math.inf (or numpy.inf which is the inf constant from numpy).

Источник

Оцените статью