[英]Haskell - resolve type error given type constraint
我正在尝试在 Haskell 中实现高斯误差 function 的数值近似。
erf :: (Floating a) => a -> a
erf x = 1.0 - poly * (exp ** (-(x ** 2)))
where p = 0.3275911
t = 1.0 / (1.0 + p * x)
a1 = 0.254829592
a2 = -0.284496736
a3 = 1.421413741
a4 = -1.453152027
a5 = 1.061405429
poly = t * (a1 + t * (a2 + t * (a3 + t * (a4 + t * a5))))
尝试加载到 GHCI 会引发以下错误:
ghci> :l stats
[1 of 1] Compiling Main ( stats.hs, interpreted )
stats.hs:2:33: error:
• Couldn't match expected type ‘a0 -> a0’ with actual type ‘a’
‘a’ is a rigid type variable bound by
the type signature for:
erf :: forall a. Floating a => a -> a
at stats.hs:1:8
• In the expression: (x ** 2)
In the second argument of ‘(**)’, namely ‘(- (x ** 2))’
In the second argument of ‘(*)’, namely ‘(exp ** (- (x ** 2)))’
• Relevant bindings include
poly :: a0 -> a0 (bound at stats.hs:10:11)
t :: a0 -> a0 (bound at stats.hs:4:11)
p :: a0 -> a0 (bound at stats.hs:3:11)
a1 :: a0 -> a0 (bound at stats.hs:5:11)
a2 :: a0 -> a0 (bound at stats.hs:6:11)
a3 :: a0 -> a0 (bound at stats.hs:7:11)
x :: a (bound at stats.hs:2:5)
(Some bindings suppressed; use -fmax-relevant-binds=N or -fno-max-relevant-binds)
stats.hs:4:32: error:
• Couldn't match expected type ‘a0 -> a0’ with actual type ‘a’
‘a’ is a rigid type variable bound by
the type signature for:
erf :: forall a. Floating a => a -> a
at stats.hs:1:8
• In the second argument of ‘(*)’, namely ‘x’
In the second argument of ‘(+)’, namely ‘p * x’
In the second argument of ‘(/)’, namely ‘(1.0 + p * x)’
• Relevant bindings include
t :: a0 -> a0 (bound at stats.hs:4:11)
p :: a0 -> a0 (bound at stats.hs:3:11)
a1 :: a0 -> a0 (bound at stats.hs:5:11)
a2 :: a0 -> a0 (bound at stats.hs:6:11)
a3 :: a0 -> a0 (bound at stats.hs:7:11)
a4 :: a0 -> a0 (bound at stats.hs:8:11)
x :: a (bound at stats.hs:2:5)
(Some bindings suppressed; use -fmax-relevant-binds=N or -fno-max-relevant-binds)
Failed, modules loaded: none.
ghci>
我在 function 的where
部分尝试a
各种铸件,但无济于事。 如何修复此 function?
exp:: Floating a => a -> a
是一个带参数的function 。 因此,像exp ** (x ** 2)
这样的表达式没有多大意义。
我们可以使用参数调用exp
,例如exp (-(x ** 2))
或更简单的exp (-x*x)
:
erf :: Floating a => a -> a
erf x = 1.0 - poly * exp (-x*x)
where p = 0.3275911
t = 1.0 / (1.0 + p * x)
a1 = 0.254829592
a2 = -0.284496736
a3 = 1.421413741
a4 = -1.453152027
a5 = 1.061405429
poly = t * (a1 + t * (a2 + t * (a3 + t * (a4 + t * a5))))
例如:
Prelude> erf 0
9.999999717180685e-10
Prelude> erf 1
0.8427006897475899
Prelude> erf 2
0.9953221395812188
Prelude> erf 3
0.9999778948511022
Prelude> erf 4
0.9999999845397042
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.