Как написать бесконечность в питоне
Перейти к содержимому

Как написать бесконечность в питоне

  • автор:

How to Represent an Infinite Number in Python?

Infinity is an undefined number which can be negative or positive. A number is used as infinity; sometimes, the sum of two numeric values may be a numeric but different pattern; it may be a negative or positive value.

It is used to compare the solution in algorithms for the best solution. Generally, a value set at initial may be positive or negative infinity; we have to take care that no input value is bigger or smaller.

Infinity in Python

In Python, there is no way or method to represent infinity as an integer. This matches the fundamental characteristic of many other popular programming languages. But due to python being dynamically typed language, you can use float(inf) as an integer to represent it as infinity.

Therefore in python, we cannot represent infinity, or we can say that there is no way to show the infinity as an integer. But we can use float (inf) as an integer.

In Python, positive infinity and negative infinity can be represented by:

  • Positive infinity: inf
  • Negative infinity: -inf

Python Program to Define Positive and Negative Infinity Number

Example

Represent Positive and Negative Infinity Using the Math Module

To determine the infinity number, you can use the python math module.

Note: This will work with only python 3.5 or higher version of python.

Syntax:

  • Positive infinity: math.inf
  • Negative infinity: -math.inf

Positive infinity number is greatest, and the negative infinity number is the smallest of all numbers.

In comparison, positive infinity is always bigger than every natural number.

(i.e. 0,1,2. +∞. Positive integer and +infinity.)

In comparison, negative infinity is smaller than the negative number.

(i.e., ∞-. -2,-1,0, 1,.2,3. – negative infinity and -integer.)

Python Program to Check If the Number Is Infinite

In the above example, we are using the using isinf method of math library to check if the number is infinity or not.

Represent Positive and Negative Infinity Using the Decimal Module

You can define positive and negative Infinity by using the decimal module.

Syntax:

  • Positive Infinity: Decimal(‘Infinity’)
  • Negative Infinity: Decimal(‘-Infinity’)

Represent Positive and Negative Infinity Using Numpy Library

You can define positive and negative Infinity by using the inf module of the NumPy library

Syntax:

  • Positive Infinity: np.inf
  • Negative Infinity: -np.inf

Check If Positive Infinity Number Is Equal to Negative Infinity Number

You can simple check if the positive infinity number is equal to negative infinity number using simple “==” operator, and the output is always false.

Arithmetic operations on infinity number will give an infinite number

If you perform any arithmetic operation with positive or negative infinity numbers, the result will always be an endless number.

# Math Module

In addition to the built-in round function, the math module provides the floor , ceil , and trunc functions.

floor , ceil , trunc , and round always return a float .

round always breaks ties away from zero.

floor , ceil , and trunc always return an Integral value, while round returns an Integral value if called with one argument.

round breaks ties towards the nearest even number. This corrects the bias towards larger numbers when performing a large number of calculations.

# Warning!

As with any floating-point representation, some fractions cannot be represented exactly. This can lead to some unexpected rounding behavior.

# Warning about the floor, trunc, and integer division of negative numbers

Python (and C++ and Java) round away from zero for negative numbers. Consider:

# Trigonometry

# Calculating the length of the hypotenuse

# Converting degrees to/from radians

All math functions expect radians so you need to convert degrees to radians:

All results of the inverse trigonometic functions return the result in radians, so you may need to convert it back to degrees:

# Sine, cosine, tangent and inverse functions

Apart from the math.atan there is also a two-argument math.atan2 function, which computes the correct quadrant and avoids pitfalls of division by zero:

# Hyperbolic sine, cosine and tangent

# Logarithms

math.log(x) gives the natural (base e ) logarithm of x .

math.log can lose precision with numbers close to 1, due to the limitations of floating-point numbers. In order to accurately calculate logs close to 1, use math.log1p , which evaluates the natural logarithm of 1 plus the argument:

math.log10 can be used for logs base 10:

When used with two arguments, math.log(x, base) gives the logarithm of x in the given base (i.e. log(x) / log(base) .

# Constants

math modules includes two commonly used mathematical constants.

  • math.pi — The mathematical constant pi
  • math.e — The mathematical constant e (base of natural logarithm)

Python 3.5 and higher have constants for infinity and NaN ("not a number"). The older syntax of passing a string to float() still works.

# Infinity and NaN ("not a number")

In all versions of Python, we can represent infinity and NaN ("not a number") as follows:

In Python 3.5 and higher, we can also use the defined constants math.inf and math.nan :

The string representations display as inf and -inf and nan :

We can test for either positive or negative infinity with the isinf method:

We can test specifically for positive infinity or for negative infinity by direct comparison:

Python 3.2 and higher also allows checking for finiteness:

Comparison operators work as expected for positive and negative infinity:

But if an arithmetic expression produces a value larger than the maximum that can be represented as a float , it will become infinity:

However division by zero does not give a result of infinity (or negative infinity where appropriate), rather it raises a ZeroDivisionError exception.

Arithmetic operations on infinity just give infinite results, or sometimes NaN:

NaN is never equal to anything, not even itself. We can test for it is with the isnan method:

NaN always compares as "not equal", but never less than or greater than:

Arithmetic operations on NaN always give NaN. This includes multiplication by -1: there is no "negative NaN".

There is one subtle difference between the old float versions of NaN and infinity and the Python 3.5+ math library constants:

# Pow for faster exponentiation

Using the timeit module from the command line:

The built-in ** operator often comes in handy, but if performance is of the essence, use math.pow. Be sure to note, however, that pow returns floats, even if the arguments are integers:

# Copying signs

In Python 2.6 and higher, math.copysign(x, y) returns x with the sign of y . The returned value is always a float .

# Imaginary Numbers

Imaginary numbers in Python are represented by a "j" or "J" trailing the target number.

# Complex numbers and the cmath module

The cmath module is similar to the math module, but defines functions appropriately for the complex plane.

First of all, complex numbers are a numeric type that is part of the Python language itself rather than being provided by a library class. Thus we don’t need to import cmath for ordinary arithmetic expressions.

Note that we use j (or J ) and not i .

We must use 1j since j would be the name of a variable rather than a numeric literal.

We have the real part and the imag (imaginary) part, as well as the complex conjugate :

The built-in functions abs and complex are also part of the language itself and don’t require any import:

The complex function can take a string, but it can’t have spaces:

But for most functions we do need the module, for instance sqrt :

Naturally the behavior of sqrt is different for complex numbers and real numbers. In non-complex math the square root of a negative number raises an exception:

Functions are provided to convert to and from polar coordinates:

The mathematical field of complex analysis is beyond the scope of this example, but many functions in the complex plane have a "branch cut", usually along the real axis or the imaginary axis. Most modern platforms support "signed zero" as specified in IEEE 754, which provides continuity of those functions on both sides of the branch cut. The following example is from the Python documentation:

The cmath module also provides many functions with direct counterparts from the math module.

In addition to sqrt , there are complex versions of exp , log , log10 , the trigonometric functions and their inverses ( sin , cos , tan , asin , acos , atan ), and the hyperbolic functions and their inverses ( sinh , cosh , tanh , asinh , acosh , atanh ). Note however there is no complex counterpart of math.atan2 , the two-argument form of arctangent.

The constants pi and e are provided. Note these are float and not complex .

The cmath module also provides complex versions of isinf , and (for Python 3.2+) isfinite . See "Infinity and NaN

(opens new window) ". A complex number is considered infinite if either its real part or its imaginary part is infinite.

Likewise, the cmath module provides a complex version of isnan . See "Infinity and NaN

(opens new window) ". A complex number is considered "not a number" if either its real part or its imaginary part is "not a number".

Note there is no cmath counterpart of the math.inf and math.nan constants (from Python 3.5 and higher)

In Python 3.5 and higher, there is an isclose method in both cmath and math modules.

Как написать бесконечность в питоне

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

Elias Zamaria's user avatar

13 Answers 13

In Python, you can do:

In Python 3.5, you can do:

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:

would return true.

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 negative infinity:

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

Sнаđошƒаӽ's user avatar

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 .

Lenar Hoyt's user avatar

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

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

Thus the check i < » holds True for any integer i .

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

Also if you use SymPy you can use sympy.oo

USERNAME GOES HERE's user avatar

Infinity

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

2. Using Python’s math module

3. Integer maxsize

4. Using Python’s decimal module

5. Using Numpy Library

Erick Mwazonga's user avatar

For Positive Infinity

For Negative Infinity

Omar's user avatar

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

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *