Decimals.jl: Arbitrary precision decimal floating point arithmetics in Julia
The Decimals package provides basic data type and functions for arbitrary precision decimal floating point arithmetic in Julia. It supports addition, subtraction, negation, multiplication, division, and equality operations.
Why is this needed? The following code in Julia gives an answer
julia> 0.1 + 0.2
0.30000000000000004
In words, the binary floating point arithmetics implemented in computers has finite resolution - not all real numbers (even within the limits) can be expressed exactly. While many scientific and engineering fields can handle this behavior, it is not acceptable in fields like finance, where it's important to be able to trust that $0.30 is actually 30 cents, rather than 30.000000000000004 cents.
To convert back to a string or a number (float in this case):
julia> x =decimal("0.2");
julia>string(x)
"0.2"
julia>number(x)
0.2
It is also possible to call the Decimal constructor directly, by specifying the sign (s), coefficient (c), and exponent (q):
julia>Decimal(1,2,-2)
The numerical value of a Decimal is given by (-1)^s * c * 10^q. s must be 0 (positive) or 1 (negative); c must be non-negative; c and q must be integers.
Unlike another Julia package called DecFP, which aims at implementing the IEEE 754-2008 standard introducing 32, 64, and 64-bit precisions (decimal32, decimal64 and decimal128, respectively), this package allows arbitrary precision. Note, however, that in comparision with DecFP, which is is essentially a wrapper for a specialized Intel® Decimal Floating-Point Math Library, the present package is more computationally demanding. If more computational efficiency is demanded, functions from libmpdec library can be called directly.
请发表评论