精度损失'sqrt'Haskell

Kon*_*nos 1 haskell

在ghci终端中,我使用sqrt函数计算了一些使用Haskell的方程式.

我注意到sqrt,当我的结果被简化时,我有时会失去精确度.

例如,

sqrt 4 * sqrt 4 = 4 -- This works well!
sqrt 2 * sqrt 2 = 2.0000000000000004 -- Not the exact result.
Run Code Online (Sandbox Code Playgroud)

通常情况下,我会期待结果2.

有没有办法获得正确的简化结果?
这在Haskell中如何工作?

Mic*_*ael 6

Haskell中有可用的精确数字库.想到的两个是cyclotomic数字包中的CReal模块.(数字不支持您可能喜欢的复数上的所有操作,但整数和有理数的平方根都在域中.)Cyclotomic

>>> import Data.Complex.Cyclotomic 
>>> sqrtInteger 2
e(8) - e(8)^3
>>> toReal $ sqrtInteger 2 
Just 1.414213562373095     -- Maybe Double
>>> sqrtInteger 2 * sqrtInteger 2
2
>>> toReal $ sqrtInteger 2 * sqrtInteger 2
Just 2.0
>>> rootsQuadEq 3 2 1
Just (-1/3 + 1/3*e(8) + 1/3*e(8)^3,-1/3 - 1/3*e(8) - 1/3*e(8)^3)
>>> let eq x  = 3*x*x + 2*x + 1
>>> eq (-1/3 + 1/3*e(8) + 1/3*e(8)^3)
0
>>> import Data.Number.CReal 
>>> sqrt 2 :: CReal
1.4142135623730950488016887242096980785697 -- Show instance cuts off at 40th place
>>> sqrt 2 * sqrt 2 :: CReal
2.0
>>> sin 3  :: CReal
0.1411200080598672221007448028081102798469
>>> sin 3*sin 3 + cos 3*cos 3 :: CReal
1.0
Run Code Online (Sandbox Code Playgroud)