[swift-evolution] Pre-proposal: Safer Decimal Calculations
rainer at brockerhoff.net
Wed Mar 23 07:26:51 CDT 2016
On 3/22/16 23:20, Michael Gottesman via swift-evolution wrote:
>> On Mar 18, 2016, at 3:42 PM, Rainer Brockerhoff via swift-evolution <swift-evolution at swift.org> wrote:
>> First draft towards a tentative pre-proposal:
>> Pre-proposal: Safer Decimal Calculations
>> Proposal: TBD
>> Author(s): Rainer Brockerhoff
>> Status: TBD
>> Review manager: TBD
>> Full Decimal type proposal
>> There are cogent arguments that prior art/habits and the already complex
>> interactions between Double, Float, Float80 and CGFloat are best left alone.
>> However, there remains a need for a precise implementation of a workable
>> Decimal value type for financial calculations. IMHO repurposing the
>> existing NSDecimalNumber from Objective-C is not the best solution.
>> As most experienced developers know, the standard solution for financial
>> calculations is to internally store fixed-point values — usually but not
>> always in cents — and then print the “virtual” point (or decimal comma,
>> for the rest of us) on output.
>> I propose, therefore, an internal data layout like this:
>> UInt16 - position of the “virtual” point, starting at 0
>> UInt16 - data array size - 1
>> [Int32] - contiguous data array, little-endian order, grown as needed.
>> Note that both UInt16 fields being zero implies that the number is
>> reduced to a 32-bit Integer. Number literals in Swift can be up to 2048
>> bits in size, so the maximum data array size would be 64, although it
>> could conceivably grow beyond that. The usual cases of the virtual point
>> position being 0 or 2 could be aggressively optimized for normal
>> arithmetic operators.
>> Needless to say such a Decimal number would accept and represent
>> literals such as 0.01 with no problems. It would also serve as a BigNum
>> implementation for most purposes.
>> No doubt implementing this type in the standard library would allow for
>> highly optimized implementations for all major CPU platforms. In
>> particular, the data array should probably be [Int64] for 64-bit platforms.
> Rainer: I quickly skimmed this. Just to make sure I am understanding 100%: you are proposing a fixed point decimal calculation or a floating point decimal calculation. The former, no?
Right, fixed-point. (NSDecimalNumber is decimal floating-point, of course).
I'll be updating my pre-proposal in a few days with the received feedback.
Rainer Brockerhoff <rainer at brockerhoff.net>
Belo Horizonte, Brazil
"In the affairs of others even fools are wise
In their own business even sages err."
More information about the swift-evolution