【问题标题】:Why do large number operations return negative numbers at a certain point with 'ints' in Haskell?为什么大量运算在 Haskell 中使用“整数”在某个点返回负数?
【发布时间】:2016-05-21 16:40:15
【问题描述】:

具有以下功能:
factorial :: Int -> Int
factorial n = product [1..n]

小于21的参数返回正确的值。例如: factorial 20 返回 2432902008176640000,但 factorial 21 返回 -4249290049419214848,即使该值不是负数也是不正确的。

我知道应该使用这些尺寸数字Integer,但是这里发生的具体错误是什么?为什么?

【问题讨论】:

标签: haskell numbers int


【解决方案1】:

Int 在 Haskell 中是具有有限范围的整数的固定精度表示。与大多数固定精度整数表示的情况一样,一个算术运算会创建一个太大或太小而无法表示的整数(这称为 整数溢出,如 Mephy 所述)将将其结果包装,将其截断为最低有效位。例如:

λ> maxBound + 1 :: Int
-9223372036854775808

λ> (maxBound + 1 :: Int) == minBound
True

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-12-14
    • 1970-01-01
    • 2022-06-15
    • 2011-04-27
    • 1970-01-01
    • 2021-02-08
    • 1970-01-01
    相关资源
    最近更新 更多