How to Represent an Infinite Number in Python

How can I represent an infinite number in Python?

In Python, you can do:

test = float("inf")

In Python 3.5, you can do:

import math
test = math.inf

And then:

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:

float('inf') < Ellipsis

would return true.

Represent infinity as an integer in Python 2.7

To summarise what was said in the comments

There is no way to represent infinity as an integer in Python. This matches the behaviour of many other languages. However, due to Python's dynamic typing system, you can use float('inf') in place of an integer, and in most situations it will behave as you would expect.

As far as creating a 'double' for infinity, in Python there is just one floating point type, called float, unlike other languages such as Java which uses the term float and double for floating point numbers with different precision. In Python, floating point numbers usually use double-precision, so they act the same as doubles in Java.

how to express very big infinite number in python similar to C++ INT.INF?

For infinitely small or large numbers simply use math.inf after importing math.

import math

#x is infinitely small
x = float('-inf')

#y is infinitely large
y = float('+inf')

How to use infinity in python

Use float("inf") or math.inf

See also How can I represent an infinite number in Python?

>>> float("inf") > 5
True
>>> float("inf") < 10**100
False
>>> import math
>>> float("inf") == math.inf
True

If you need to use some other value than "inf" for infinity, such as '-' in your example, you could try/except it, either

  • checking if the initial value is your target string (if a == '-':)
  • parsing the error calling float on it (if "'-'" in str(err_string):)
try:
a = float(a)
except ValueError as ex:
# special-case for ValueError: could not convert string to float: '-'
if "'-'" in str(ex).split(":")[-1]:
a = float("inf")
else: # re-raise other ValueErrors
raise ex

I need to represent infinite as integer in python 3

There is no reason to check membership in a massive list which will eat up a ton of memory. You can just check what you age endswith.

age = input('Type age: ')
if age.endswith('11') or age.endswith('12') or age.endswith('13'):
term = 'th'
elif age.endswith('1'):
term = 'st'
elif age.endswith('2'):
term = 'nd'
elif age.endswith('3'):
term = 'rd'
else:
term = 'th'

if int(age) >= 130:
print("C'mon! you can't be THAT old, you geezer!\nStill, here you go:")
message = f"Happy {age}{term} birthday!"

print(message)

How to implement negative infinity in python?

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



Related Topics



Leave a reply



Submit