Checking if float is equivalent to an integer value in python

Question:

In Python 3, I am checking whether a given value is triangular, that is, it can be represented as n * (n + 1) / 2 for some positive integer n.

Can I just write:

import math

def is_triangular1(x):
    num = (1 / 2) * (math.sqrt(8 * x + 1) - 1)
    return int(num) == num

Or do I need to do check within a tolerance instead?

epsilon = 0.000000000001
def is_triangular2(x):
    num = (1 / 2) * (math.sqrt(8 * x + 1) - 1)
    return abs(int(num) - num) < epsilon

I checked that both of the functions return same results for x up to 1,000,000. But I am not sure if generally speaking int(x) == x will always correctly determine whether a number is integer, because of the cases when for example 5 is represented as 4.99999999999997 etc.

As far as I know, the second way is the correct one if I do it in C, but I am not sure about Python 3.

Asked By: Sunny88

||

Answers:

Python still uses the same floating point representation and operations C does, so the second one is the correct way.

Answered By: Aurojit Panda

You’ll want to do the latter. In Programming in Python 3 the following example is given as the most accurate way to compare

def equal_float(a, b):
    #return abs(a - b) <= sys.float_info.epsilon
    return abs(a - b) <= chosen_value #see edit below for more info

Also, since epsilon is the “smallest difference the machine can distinguish between two floating-point numbers”, you’ll want to use <= in your function.

Edit: After reading the comments below I have looked back at the book and it specifically says “Here is a simple function for comparing floats for equality to the limit of the machines accuracy”. I believe this was just an example for comparing floats to extreme precision but the fact that error is introduced with many float calculations this should rarely if ever be used. I characterized it as the “most accurate” way to compare in my answer, which in some sense is true, but rarely what is intended when comparing floats or integers to floats. Choosing a value (ex: 0.00000000001) based on the “problem domain” of the function instead of using sys.float_info.epsilon is the correct approach.

Thanks to S.Lott and Sven Marnach for their corrections, and I apologize if I led anyone down the wrong path.

Answered By: Dan Roberts

Python does have a Decimal class (in the decimal module), which you could use to avoid the imprecision of floats.

Answered By: Paul D. Waite

I think the module decimal is what you need

Answered By: eyquem

You can round your number to e.g. 14 decimal places or less:

 >>> round(4.999999999999997, 14)
 5.0

PS: double precision is about 15 decimal places

Answered By: JBernardo

Both your implementations have problems. It actually can happen that you end up with something like 4.999999999999997, so using int() is not an option.

I’d go for a completely different approach: First assume that your number is triangular, and compute what n would be in that case. In that first step, you can round generously, since it’s only necessary to get the result right if the number actually is triangular. Next, compute n * (n + 1) / 2 for this n, and compare the result to x. Now, you are comparing two integers, so there are no inaccuracies left.

The computation of n can be simplified by expanding

(1/2) * (math.sqrt(8*x+1)-1) = math.sqrt(2 * x + 0.25) - 0.5

and utilizing that

round(y - 0.5) = int(y)

for positive y.

def is_triangular(x):
    n = int(math.sqrt(2 * x))
    return x == n * (n + 1) / 2
Answered By: Sven Marnach

Under the hood, Python’s float type is a C double.

The most robust way would be to get the nearest integer to num, then test if that integers satisfies the property you’re after:

import math
def is_triangular1(x):
    num = (1/2) * (math.sqrt(8*x+1)-1 )
    inum = int(round(num))
    return inum*(inum+1) == 2*x  # This line uses only integer arithmetic
Answered By: Daniel Stutzbach

It is hard to argue with standards.

In C99 and POSIX, the standard for rounding a float to an int is defined by nearbyint() The important concept is the direction of rounding and the locale specific rounding convention.

Assuming the convention is common rounding, this is the same as the C99 convention in Python:

#!/usr/bin/python

import math

infinity = math.ldexp(1.0, 1023) * 2

def nearbyint(x): 
   """returns the nearest int as the C99 standard would"""

   # handle NaN
   if x!=x:
       return x      

   if x >= infinity:
       return infinity

   if x <= -infinity:
       return -infinity

   if x==0.0:
       return x

   return math.floor(x + 0.5)

If you want more control over rounding, consider using the Decimal module and choose the rounding convention you wish to employ. You may want to use Banker’s Rounding for example.

Once you have decided on the convention, round to an int and compare to the other int.

Answered By: user648852

floats can exactly represent all integers in their range – floating-point equality is only tricky if you care about the bit after the point. So, as long as all of the calculations in your formula return whole numbers for the cases you’re interested in, int(num) == num is perfectly safe.

So, we need to prove that for any triangular number, every piece of maths you do can be done with integer arithmetic (and anything coming out as a non-integer must imply that x is not triangular):

To start with, we can assume that x must be an integer – this is required in the definition of ‘triangular number’.

This being the case, 8*x + 1 will also be an integer, since the integers are closed under + and * .

math.sqrt() returns float; but if x is triangular, then the square root will be a whole number – ie, again exactly represented.

So, for all x that should return true in your functions, int(num) == num will be true, and so your istriangular1 will always work. The only sticking point, as mentioned in the comments to the question, is that Python 2 by default does integer division in the same way as C – int/int => int, truncating if the result can’t be represented exactly as an int. So, 1/2 == 0. This is fixed in Python 3, or by having the line

from __future__ import division

near the top of your code.

Answered By: lvc

There is is_integer function in python float type:

>>> float(1.0).is_integer()
True
>>> float(1.001).is_integer()
False
>>> 
Answered By: ndpu

Consider using NumPy, they take care of everything under the hood.

import numpy as np

result_bool = np.isclose(float1, float2)

Answered By: NoName

Python has unlimited integer precision, but only 53 bits of float precision. When you square a number, you double the number of bits it requires. This means that the ULP of the original number is (approximately) twice the ULP of the square root.

You start running into issues with numbers around 50 bits or so, because the difference between the fractional representation of an irrational root and the nearest integer can be smaller than the ULP. Even in this case, checking if you are within tolerance will do more harm than good (by increasing the number of false positives).

For example:

>>> x = (1 << 26) - 1
>>> (math.sqrt(x**2)).is_integer()
True
>>> (math.sqrt(x**2 + 1)).is_integer()
False
>>> (math.sqrt(x**2 - 1)).is_integer()
False

>>> y = (1 << 27) - 1
>>> (math.sqrt(y**2)).is_integer()
True
>>> (math.sqrt(y**2 + 1)).is_integer()
True
>>> (math.sqrt(y**2 - 1)).is_integer()
True
>>> (math.sqrt(y**2 + 2)).is_integer()
False
>>> (math.sqrt(y**2 - 2)).is_integer()
True
>>> (math.sqrt(y**2 - 3)).is_integer()
False

You can therefore rework the formulation of your problem slightly. If an integer x is a triangular number, there exists an integer n such that x = n * (n + 1) // 2. The resulting quadratic is n**2 + n - 2 * x = 0. All you need to know is if the discriminant 1 + 8 * x is a perfect square. You can compute the integer square root of an integer using math.isqrt starting with python 3.8. Prior to that, you could use one of the algorithms from Wikipedia, implemented on SO here.

You can therefore stay entirely in python’s infinite-precision integer domain with the following one-liner:

def is_triangular(x):
    return math.isqrt(k := 8 * x + 1)**2 == k

Now you can do something like this:

>>> x = 58686775177009424410876674976531835606028390913650409380075
>>> math.isqrt(k := 8 * x + 1)**2 == k
True
>>> math.isqrt(k := 8 * (x + 1) + 1)**2 == k
False

>>> math.sqrt(k := 8 * x + 1)**2 == k
False

The first result is correct: x in this example is a triangular number computed with n = 342598234604352345342958762349.

Answered By: Mad Physicist
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.