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