Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
518 views
in Technique[技术] by (71.8m points)

floating point - Checking if float is equivalent to an integer value in python

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There is is_integer function in python float type:

>>> float(1.0).is_integer()
True
>>> float(1.001).is_integer()
False
>>> 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...