为什么我在朱莉娅这些简单的操作得到不正确的结果? [英] Why am I getting incorrect results for these simple operations in Julia?

查看:132
本文介绍了为什么我在朱莉娅这些简单的操作得到不正确的结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经开始使用Julia语言了,但即使是基本操作,我也很惊讶地发现看起来不正确的结果:

 朱莉娅> 0.05 * 0.05 
0.0025000000000000005



 朱莉娅> 1.0-0.85-0.1 
0.05000000000000002

这怎么可能?我能做些什么来获得确切的结果?

解决方案


我很惊讶看起来不正确结果甚至基本的操作[...]这怎么可能?


二进制IEEE-754浮点数( Julia使用的)不能代表这样的数字例如,当你在Julia中写入 0.05 时,这个数字就是0.05,0.85和0.1。机器操作的数字非常接近实际的数字0.05,但不是0.05正好0.05。因此,你不能指望像 0.05 * 0.05 这样的Julia表达式恰好估计为0.0025。

更违反直觉的例子?试试

  julia> 1-0.2-0.2-0.2-0.2-0.2 
5.551115123125783e-17

julia> 0.6 / 0.2 == 3
false

如果您有兴趣(即使您我不强烈推荐
David Goldberg的 每个计算机科学家应该知道的有关浮点运算的知识 。您可能也对这个






p>我能做些什么来获得确切的结果?

你只是操纵有理数?如果是这样,知道朱莉娅提供了一个 类型,即允许您精确地表示分数的类型。



默认使用的理性类型, Rational {Int64} 能够表示任何有理数,其分子和分母落在64位整数的范围内。
您可以使用这个有理数类型来对有理数进行精确的操作(禁止整数溢出):

pre $ code $ julia> 1 // 20 * 1 // 20
1 // 400

julia> 1 - 17 // 20 - 1 // 10
1 // 20

如果你想任意精度有理数,你可以使用 Rational {BigInt} 类型(参见阿尔法先生的评论

I've started using the Julia language, but I'm surprised to get seemingly incorrect results with even basic operations:

julia> 0.05*0.05
0.0025000000000000005

and

julia> 1.0-0.85-0.1
0.05000000000000002

How can this be? And what can I do to obtain exact results?

解决方案

I'm surprised to get seemingly incorrect results with even basic operations [...] How can this be?

Binary IEEE-754 floating-point numbers (which Julia uses) cannot represent numbers such as 0.05, 0.85, and 0.1 exactly.

For instance, when you write 0.05 in Julia, the number that the machine manipulates is a number very close to the actual number 0.05, but not exactly 0.05. Therefore, you cannot expect Julia expressions such as 0.05*0.05 to evaluate to exactly 0.0025.

More counterintuitive examples? Try

julia> 1-0.2-0.2-0.2-0.2-0.2
5.551115123125783e-17

julia> 0.6/0.2 == 3
false

If you're interested (and even if you're not!), I strongly recommend David Goldberg's What every computer scientist should know about floating-point arithmetic. You may also be interested in this related answer of mine on the TeX sister site.


And what can I do to obtain exact results?

Are you only manipulating rational numbers? If so, know that Julia provides a rational types, i.e. types that allow you to represent fractions exactly.

The rational type used by default, Rational{Int64}, is capable of representing any rational number whose numerator and denominator fall in the range of 64-bit integers. You can use this rational type to carry out exact operations (barring integer overflow) on rational numbers:

julia> 1//20 * 1//20
1//400

julia> 1 - 17//20 - 1//10
1//20

Moreover, if you want arbitrary-precision rational numbers, you can use the Rational{BigInt} type (see Mr Alpha's comment)

这篇关于为什么我在朱莉娅这些简单的操作得到不正确的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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