为什么ghci 说1.1 + 1.1 + 1.1 >3.3 是真的吗? [英] Why does ghci say that 1.1 + 1.1 + 1.1 > 3.3 is True?

查看:21
本文介绍了为什么ghci 说1.1 + 1.1 + 1.1 >3.3 是真的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近正在阅读 Haskell 教程,并在交互式 ghci shell 中尝试一些简单的 Haskell 表达式时注意到了这种行为:

I've been going through a Haskell tutorial recently and noticed this behaviour when trying some simple Haskell expressions in the interactive ghci shell:

Prelude> 1.1 + 1.1 == 2.2
True
Prelude> 1.1 + 1.1 + 1.1 == 3.3
False
Prelude> 1.1 + 1.1 + 1.1 > 3.3
True
Prelude> 1.1 + 1.1 + 1.1
3.3000000000000003

有人知道这是为什么吗?

Does anybody know why that is?

推荐答案

因为 1.13.3浮点数.十进制小数,例如 .1 或 .3,不能完全用二进制浮点数表示..1 表示 1/10.要以二进制表示,其中每个小数位代表 1/2n(1/2、1/4、1/8 等),您需要无限数量的数字,0.000110011... 无限重复.

Because 1.1 and 3.3 are floating point numbers. Decimal fractions, such as .1 or .3, are not exactly representable in a binary floating point number. .1 means 1/10. To represent that in binary, where each fractional digit represents 1/2n (1/2, 1/4, 1/8, etc), you would need an infinite number of digits, 0.000110011... repeating infinitely.

这与表示以 10 为基数的 1/3 完全相同.在以 10 为基数的情况下,您需要无限数量的数字,0.33333...永远,才能准确地表示 1/3.因此,在基数 10 中工作,您通常会舍入到 0.33 之类的值.但是如果你把它的三个副本加起来,你会得到 0.99,而不是 1.

This is exactly the same problem as representing, say, 1/3 in base 10. In base 10, you would need an infinite number of digits, .33333... forever, to represent 1/3 exactly. So working in base 10, you usually round, to something like .33. But if you add up three copies of that, you get .99, not 1.

有关该主题的更多信息,请阅读每个计算机科学家应该做的事情了解浮点运算.

For far more information on the topic, read What Every Computer Scientist Should Know About Floating Point Arithmetic.

为了在 Haskell 中更精确地表示有理数,您始终可以使用有理数数据类型,比率;再加上 bignums(任意大整数,Haskell 中的 Integer,而不是固定大小的 Int)作为分子和分母的类型,你可以表示任意精确的有理数,但速度明显低于浮点数,浮点数在硬件中实现并针对速度进行了优化.

For representing rational numbers more precisely in Haskell, you can always use the rational data type, Ratio; coupled with bignums (arbitrarily large integers, Integer in Haskell, as opposed to Int which are fixed size) as the type for numerator and denominator, you can represent arbitrarily precise rational numbers, but at a significantly slower speed than floating point numbers, which are implemented in hardware and optimized for speed.

浮点数是一种优化,适用于科学和数值计算,以精度换取高速,允许您在短时间内执行大量计算,只要您了解舍入及其方式影响你的计算.

Floating point numbers are an optimization, for scientific and numerical computation, that trade off precision for high speed, allowing you to perform a very large number of computations in a small time, as long as you are aware of rounding and how it affects your computations.

这篇关于为什么ghci 说1.1 + 1.1 + 1.1 >3.3 是真的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆