Julia中的精确十进制算术 [英] Exact decimal arithmetic in Julia
问题描述
由于浮点数学的性质,.4* .4
= 0.16000000000000003
在 Julia 中.我想以 CPU 高效的方式获得 0.16
的数学正确答案.我知道 round() 有效,但这需要事先了解答案占据的小数位数,因此它不是通用解决方案.
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.
推荐答案
一些选项:
使用内置的
Rational
类型.最准确和最快的方法是
Use the inbuilt
Rational
type. The most accurate and fastest way would be
16//100 * 16//100
16//100 * 16//100
如果你使用非常大的数字,这些可能会溢出,在这种情况下你可以使用 BigInt
s 代替,
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)
(您实际上不需要将它们全部包装在 big
中,因为有理数会自动提升).
(you don't actually need to wrap them all in big
s, as the rationals will promote automatically).
您也可以使用 rationalize(0.16)
,但这可能不够准确或高效,因为文字 0.16
已经转换为 Float64
到 Julia 看到它时,所以您正在转换为二进制浮点,然后转换为 Rational
.
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 是一个大十进制"浮点库:如它使用任意精度算法,它会比 DecFP 慢.
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屋!