How to Work with Python negative Infinity and Test Them

When dealing with sophisticated mathematical problems it may be necessary to deal with integers that exceed standard values, or those that may be lower than the negative of such infinite values.

Python is a popular and powerful general-purpose programming language. Being open source, developers and contributors are empowered to create libraries and tools that complement the functionality of Python. Scientific computing capabilities of the language have been greatly enhanced by such libraries as NumPy, Scipy, Maplotlib, and others.

With the native and add-on functionality for mathematic operations, Python developers can perform sophisticated functions, including dealing with challenging values such as infinity and negative infinity.

You may just need to ensure that the results of your calculations are less than infinity, or higher than negative infinity, to determine that your result meets the requirements of being a number that is not higher (or lower) than infinity, regardless of sign.

Most programming languages have resolved this requirement by providing you with a way to represent infinite values, and Python is no exception.

NumPy is also available to Python developers, opening a broad array of scientific computing functions with high-performance execution and array handling attributes. NumPy adheres to the IEEE standard for Binary Floating-Point for Arithmetic (IEEE standard 754).

Representing an Infinite Value in Python

One method of comparing your result to an infinite value is to specify a number range that is higher or lower than the maximum values of your content (min-1/max+1). This is of course not a true test for infinite values, but has been used in practice.

A better way in Python is to utilize the language’s functions to represent either positive or negative infinity:

  • # positive infinity
  • p_inf = float(‘inf’)

or

  • # negative infinity
  • n_inf = float(‘-inf’)

With Python 3, there are multiple methods of defining negative infinity:

  • Specify Min(x) – 1 (one less than the minimum value)
  • Test explicitly for the value ‘None’ when comparing values
  • Define your own new data type with the value of an integer or negative infinity to manage comparison logic correctly

You can also utilize explicit values for positive or negative values using:

  • math.inf (positive infinity)
  • -math.inf (negative infinity)

How to Test for Negative Infinity in Python

Infinity in Python

When testing results for infinite values, whether positive or negative, you can determine that condition with a simple test:

  • # by using the math library
  • import math
  • math.isinf(float (‘-inf’))  #OUTPUT:True
  • math.isinf(float (‘inf’))  #OUTPUT:True

or

# by comparing specifically to infinity

  • float(‘inf’) == float (‘inf’) #OUTPUT:True
  • float(‘-inf’) == float (‘-inf’) #OUTPUT:True

Additional code for testing positive/negative infinity

Positive

  • x == float(‘+inf’)
  • math.isinf(x) and x > 0

Negative

  • x == float(‘-inf’)
  • math.isinf(x) and x < 0

Testing for infinity with math.isinf() tests simply for infinity being true, without regard for the positive or negative attribute of the value. To determine the sign, you must explicitly test for it.

Of course, normal arithmetic calculations will not result in infinite values, but when they occur, you will want to be aware of the condition through detecting an OverflowError. This would be the preferred way of catching an infinite value (positive or negative) as opposed to having an infinite value (“inf”) unknowingly returned to your code, skewing other calculations.

Of course, if infinity or negative infinity is the actual intended result, you will want to test that exact condition for a “True” status, rather than recognizing the overflow and handling the condition differently. Overflow conditions could simply mean your answer is very large, but not necessarily infinite.

If you’re concerned with performance down to the nanosecond level, using the example that includes the math.isinf(x) combined with x > 0 will actually execute faster. While it may seem relatively unimportant to quibble over a few nanoseconds when testing a complex routine, think about web sites that will be used by thousands of users, perhaps thousands of times per day – even per hour. When you’re waiting for web site calculations and page loads, seconds can make a considerable difference. NumPy is recognized for its power and performance.

NumPy provides additional commands/syntax for testing for positive or negative infinity:

  • isneginf – tests an element for negative infinity, returning the result as a bool array
  • isinf – tests an element for positive infinity

How to Work with Negative Infinity in Python

When coding equations in Python, you should be aware of how result comparisons are going to treat your tests for values against infinity or negative infinity.

Equal Comparison

Calculations that return +inf or -inf may be different values, but from a comparison viewpoint, +inf and +inf results will always compare as equals, as will -inf and -inf results. Python makes these comparisons equal just as the IEEE floating point standard provides. So:

  • +inf = +inf
  • -inf = -inf

Comparing against +inf and -inf will always be unequal, and NaN (not a number) will be deemed unequal to both values, as well as to any other NaN value.

Unequal Comparison

Comparison for greater-than (>) or less-than (<) conditions will have the following results in Python:

  • A value including +inf is always higher than -inf
  • Values including -inf are lower than +inf
  • +inf will never be higher or lower than another +inf value
  • -inf will never be higher or lower than another -inf value
  • Comparison against NaN will result in a false condition (inf will not be considered higher or lower than Nan)
  • All values are larger than -inf
  • All values are smaller than +inf

Performing Infinity or Negative Infinity Calculations with Python

Calculations

When performing calculations with infinity or negative infinity, most results will yield an infinite value. There are exceptions to that general rule when your calculation contains infinite values in both operands:

NaN will result when multiplied by zero

Dividing a number by infinity (except infinity) yields an answer of 0.0.

If you divide positive or negative infinity by positive infinity, the result will be NaN, since it will be undefined

Subtracting will follow standard mathematical rules:

  • Inf – inf = NaN (undefined)
  • Inf – -inf = inf
  • -inf – inf = -inf
  • -inf – -inf = NaN

Adding likewise follows the rules of basic mathematics:

  • Inf + inf = inf
  • Inf + -inf = NaN
  • -inf + inf = NaN
  • -inf + -inf = -inf

Python Infinity and Negative Infinity – Caveats

Like many complex mathematical equations and results, infinity in Python has its own caveats that you need to be aware of:

  • Though most basic math functions in a Python object will not deal with infinite or negative infinite results, when you do work with infinity and negative infinity, you can still get NaN results. This is why you should test implicitly for inf and -inf rather than just testing for an OverflowError, to know just what conditions you’re dealing with, and how best to react to such conditions in your code.
  • When working with infinite integers, you may not receive under or overflow errors, causing your tests to miss infinity results, unless you test for a result of infinity or negative infinity.
  • Since calculations with NaN result in NaN being returned, use the math.isnan function to determine if the result truly is NaN, where you may have encountered an infinite value instead.
  • Keep in mind that although Python permits the expression of float(‘-NaN), the sign is not recognized. Since there is no such thing in Python as negative NaN, the function to divide -inf by inf will result in NaN, not -NaN.

It pays to validate you’re the conditions of your calculations directly, rather than assuming what NaN conditions or OverflowError are telling you.

Additional Resources

Mathematicians have long debated on whether or not negative infinity even exists, yet as a Python developer, you must surely provide for that condition within code and formulas, to avoid exceptions.

Further details and coding examples are plentiful on the web, where Python developers are happy to share experiences and code snippets.

ProgramCreek.com provides a broad sampling of NumPy coding examples related to infinity, with full explanations of syntax and results produced by the code.

If you make it your best practice to verify all calculation results for inf, -inf, NaN, and overflow conditions, your accuracy will be consistent and exceptions will be few.

Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.