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 it like this? :
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.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…