在 Haskell 中实现浮点数的下限和分形的最佳方法?



Haskell中的floor仅针对RealFrac类型类定义。我对这个类型类了解不多,我的其余代码只使用浮点数。

我找不到任何将Float转换为Int的功能.如果有,那么floor将等同于fromIntegral (fromFloating x)fract将被定义为

fract x = x - floor x

但是,正如我所说,我还没有找到任何功能可以像我想fromFloating做的事情一样。所以这是我能想到的实现fract的唯一方法:

fract x 
| x < 0 = 1 - fract (abs x)
| x < 1 = x
| otherwise = fract (x - 1)

然后当然floor xx - fract x.然而,上面的算法是O(n(,它会大大减慢速度,所以我希望有一种方法可以做到这一点,那就是恒定的时间。

正如注释所说,floor已经为浮点数实现了,frac很简单; 这段代码编译:

aDouble :: Double
aDouble = -5.675
aFloat :: Float
aFloat = 10.675
frac :: RealFrac a => a -> a
frac x = x - fromIntegral (floor x :: Integer)
main :: IO ()
main = do
putStrLn "aDouble is"
print aDouble
putStrLn "frac(aDouble) is"
print (frac aDouble)
putStrLn "aFloat is"
print aFloat
putStrLn "frac(aFloat) is"
print (frac aFloat)

并产生:

$ runhaskell /tmp/a.hs
aDouble is
-5.675
frac(aDouble) is
0.3250000000000002
aFloat is
10.675
frac(aFloat) is
0.6750002

最新更新