在Julia中精确的十进制算术 [英] Exact decimal arithmetic in Julia
问题描述
由于浮点数学的性质, .4 * .4
= 0.16000000000000003
在Julia。我想以CPU高效的方式得到 0.16
的数学正确答案。我知道round()的作品,但这需要预先知道小数位数的答案占据,所以这不是一个普遍的解决方案。 解决方案
一些选项:
$ b
-
使用内置的
Rational
类型。最准确和最快捷的方式是
$ b $ 16 // 100 * 16 // 100
如果使用的数字非常大,可能会溢出,在这种情况下,您可以使用 BigInt
s来替代,
$ $ p $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
(你实际上并不需要把它们都包装在 big
中,自动提升)。
您也可以使用 rationalize(0.16)
,但这可能不是那么准确或有效,在Julia看到它的时候,文字 0.16
已经被转换为 Float64
,所以你要转换成二进制然后转换为 Rational
。
-
DecFP.jl 包装了英特尔实施的 IEEE-754 十进制浮点数。这应该是相当快(虽然不如二进制),但具有固定的精度,所以你将不得不在一定程度上舍入。
=https://github.com/tinybike/Decimals.jl =nofollow noreferrer> Decimals.jl 是一个十进制大数的浮点库:因为它使用任意的精度算法,要比DecFP慢。
要说哪一个是最好的,需要更多关于您的预期用途的信息。 p>
Due to the nature of floating-point math, .4 * .4
= 0.16000000000000003
in Julia. I want to get the mathematically correct answer of 0.16
, in a CPU-efficient way. I know round() works, but that requires prior knowledge of the number of decimal places the answer occupies, so it isn't a general solution.
Some options:
Use the inbuilt
Rational
type. The most accurate and fastest way would be16//100 * 16//100
If you're using very big numbers these might overflow, in which case you can use BigInt
s instead,
big(16)//big(100) * big(16)//big(100)
(you don't actually need to wrap them all in big
s, as the rationals will promote automatically).
You can also use rationalize(0.16)
, but this may not be quite as accurate or efficient, as the literal 0.16
has already been converted to a Float64
by the time Julia sees it, so you're converting to a binary floating point and then to a Rational
.
DecFP.jl wraps the Intel implementation of IEEE-754 Decimal floating point. This should be reasonably fast (though not as efficient as binary), but has fixed precision, so you will have to round at some point.
Decimals.jl is a "big decimal" floating point library: as it uses arbitrary precision arithmetic, it is going to be slower than DecFP.
To say which is the best would require more information about your intended use.
这篇关于在Julia中精确的十进制算术的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!