如果我在Haskell中有一个浮点数,如何测试它是否为整数。
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
好的,虽然已经晚了一年,但我是上述修改的大粉丝:
--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
。
isInt ::(Integral a,RealFrac b)=> a-> b-> Bool
与
isInt n x = round(10 ^ fromIntegral n *(x -fromIntegral(round x)))== 0
更易于组合,易于阅读。 - Alex W
isInt(1/0) == True
。 - hvr