如何在Haskell中测试浮点数是否为整数?

26

如果我在Haskell中有一个浮点数,如何测试它是否为整数。

2个回答

40
isInt x = x == fromInteger (round x)

> isInt 2
True
> isInt 2.5
False

还要提醒一下:永远记住浮点数的全能诅咒:

> isInt (0.1^2*200)
False
> 0.1^2*200
2.0000000000000004

2
@Peter:不,根据Hoogle的结果。 - yairchu
3
请注意,isInt(1/0) == True - hvr
@hvr:有趣,这很奇怪。 - yairchu

20

好的,虽然已经晚了一年,但我是上述修改的大粉丝:

--Returns if x is an int to n decimal places
isInt :: (Integral a, RealFrac b) => b -> a -> Bool
isInt x n = (round $ 10^(fromIntegral n)*(x-(fromIntegral $ round x)))==0

比如,isInt 4.0001 3返回True,但是isInt 4.0001 4返回False。以大约10的值运行它几乎总是足够准确,浮点误差会再次给您带来问题;我通常使用7


2
我认为isInt ::(Integral a,RealFrac b)=> a-> b-> BoolisInt n x = round(10 ^ fromIntegral n *(x -fromIntegral(round x)))== 0更易于组合,易于阅读。 - Alex W

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接