【问题标题】:Computing Taylor Series of e^x with Haskell List Comprension用 Haskell 列表理解计算 e^x 的泰勒级数
【发布时间】:2014-05-28 21:58:49
【问题描述】:

我正在尝试做一个haskell one-liner来计算e^x的泰勒级数:

-- 1 + x^1/1! + x^2/2! + x^3/3! + ...
expt x = [(x^e) / (product [1..n]) | e <- [0..], n <- [1..e]]

但我一直遇到这个问题:

<interactive>:5:1:
    No instance for (Integral t0) arising from a use of `expt'
    The type variable `t0' is ambiguous
    Possible fix: add a type signature that fixes these type variable(s)
    Note: there are several potential instances:
      instance Integral Int -- Defined in `GHC.Real'
      instance Integral Integer -- Defined in `GHC.Real'
      instance Integral GHC.Types.Word -- Defined in `GHC.Real'
    In the expression: expt 2
    In an equation for `it': it = expt 2

<interactive>:5:6:
    No instance for (Num t0) arising from the literal `2'
    The type variable `t0' is ambiguous
    Possible fix: add a type signature that fixes these type variable(s)
    Note: there are several potential instances:
      instance Num Double -- Defined in `GHC.Float'
      instance Num Float -- Defined in `GHC.Float'
      instance Integral a => Num (GHC.Real.Ratio a)
        -- Defined in `GHC.Real'
      ...plus three others
    In the first argument of `expt', namely `2'
    In the expression: expt 2
    In an equation for `it': it = expt 2

我不认为我完全理解这里出了什么问题 - 有人可以向我解释一下吗?

【问题讨论】:

  • 生成器 e &lt;- [0..], n &lt;- [1..e] 看起来不对。对于 exp Taylor 总和来说,一个就不够了吗?事实上,列表推导会生成比需要更多的术语。

标签: haskell list-comprehension taylor-series


【解决方案1】:

您可以使用以下方法修复它:

 expt x = [(x ** e) / (product [1..n]) | e <- [0..], n <- [1..e]]

你的函数类型是(Fractional t, Integral t) =&gt; t -&gt; [t]

该错误表明您要为t 使用的类型不明确。实际上似乎没有这种类型。 Integral 约束的原因是您使用了^。如果将其替换为(**),则expt 的类型将更改为

(Enum t, Floating t) => t -> [t]

然后您可以使用DoubleFloat

【讨论】:

  • sum $ take 10 (expt 1.0) ==> 5.875 --- OP 的列表理解不正确
【解决方案2】:

泰勒级数的第 n 项是 x^n/n!,所以这些项的计算公式为

expt x = [x**n / (product [1..n]) | n <- [0..]]

我不知道你想用单独的 e 和 n 变量做什么。

【讨论】:

    【解决方案3】:

    试试这个:

    expt x = [(x^e) / (fromIntegral $ product [1..n]) | e <- [(0::Int)..], n <- [1..e]]
    

    我们做了两件事:

    1. e 指定了一个显式整数类型
    2. fromIntegral 将阶乘(现在是Int)转换为Fractional 实例

    您仍然可以将任何 Fractional 实例用于 x - 例如FloatDouble

    注意:对于 32 位整数,这适用于大约 12 个术语。

    【讨论】:

      猜你喜欢
      • 2014-03-27
      • 2016-01-24
      • 2020-03-01
      • 1970-01-01
      • 2017-12-10
      • 2021-12-26
      • 2016-04-26
      • 2014-02-23
      • 2015-05-15
      相关资源
      最近更新 更多