2009-07-22 7 views

答えて

24
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 
+0

クールで、そこには(好奇心から)組み込まれています – Peter

+2

@ピーター:いいえ、ホーグルによると。 – yairchu

+1

'isInt(1/0)== True'に注意してください – hvr

15

わかりましたので、これは後半年ですが、私はの修正の大ファンです上記:

--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戻りFalse10の値で実行すると、float-errorsが問題を再現できるほど正確になります。私は通常7を使用します。

関連する問題