斯卡拉。浮点数的奇怪结果 [英] Scala. Strange result with floating point numbers

查看:122
本文介绍了斯卡拉。浮点数的奇怪结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么从 3 中减去 2.99999 ... 时会得到奇怪的结果?

Why do I get strange results when subtracting 2.99999... from 3?

scala> math.sqrt(3)
res0: Double = 1.7320508075688772

scala> math.pow(res0, 2)
res1: Double = 2.9999999999999996

scala> 3 - res1
res2: Double = 4.440892098500626E-16


推荐答案

这是由于浮点精度;详细记录在
16-,32-和64-中可以表示的数字范围位IEEE-754系统?

This is due to floating point precision; well documented in What range of numbers can be represented in a 16-, 32- and 64-bit IEEE-754 systems?

此外,值得注意的是,完美的计算机无法用十进制表示sqrt(3),因为它是不合理的!

Also, its worth noting here that there is no way the perfect computer could represent sqrt(3) in decimal as it's irrational!

你真的认为sqrt(3)等于正好 1.7320508075688772吗?

Did you really think that sqrt(3) equals exactly 1.7320508075688772?

这篇关于斯卡拉。浮点数的奇怪结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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