zeroshade commented on code in PR #1663:
URL: https://github.com/apache/arrow-go/pull/1663#discussion_r4743145524


##########
arrow/decimal/decimal256.go:
##########
@@ -324,7 +324,160 @@ func scalePositiveFloat64_256(v float64, prec, scale 
int32) (float64, error) {
        return v, nil
 }
 
+// float64Parts splits a finite v into m*2^e with m < 2^53, ignoring the sign.
+func float64Parts(v float64) (m uint64, e int, ok bool) {

Review Comment:
   `float64Parts`, `roundScaledFloat64`, `roundScaledFloat64Big`, `pow10U128` 
and `bigIntOne` are copied verbatim from `decimal128/decimal128.go`. The two 
copies differ only in which powers-of-ten table they read. This is subtle 
bit-level code, and two copies will drift apart.
   
   `decimal` already imports `decimal128`, and `decimal128` can't import 
`decimal`, so could these move to a shared internal package (e.g. alongside the 
existing `decimalstr` helper) that both use? The `float64` power of ten could 
be passed in, or the shared package could keep its own exact table for scale <= 
22.



##########
arrow/decimal/decimal256.go:
##########
@@ -324,7 +324,160 @@ func scalePositiveFloat64_256(v float64, prec, scale 
int32) (float64, error) {
        return v, nil
 }
 
+// float64Parts splits a finite v into m*2^e with m < 2^53, ignoring the sign.
+func float64Parts(v float64) (m uint64, e int, ok bool) {
+       b := math.Float64bits(v)
+       m = b & (1<<52 - 1)
+       switch exp := int(b>>52) & 0x7ff; exp {
+       case 0x7ff:
+               return 0, 0, false
+       case 0:
+               return m, -1074, true
+       default:
+               return m | 1<<52, exp - 1075, true
+       }
+}
+
+// roundScaledFloat64 returns the exact product v*10^scale of a non-negative v,
+// rounded to the nearest integer with ties to even, as the 128-bit value 
hi:lo.
+// With v = m*2^e, m < 2^53 and 10^scale < 2^74 for scale <= 22, so m*10^scale
+// fits in 127 bits and is computed exactly, and no float64 rounding happens
+// before the final one. ok is false when scale > 22, v is not finite, or the
+// result needs more than 127 bits; the caller then needs the big.Int path.
+func roundScaledFloat64(v float64, scale int32) (hi, lo uint64, ok bool) {
+       if scale < 0 || scale > 22 {
+               return 0, 0, false
+       }
+       // 10^scale is exact in float64 here. Below 2^52 every half-integer is a
+       // float64, so unless p itself is one, the exact product lies strictly
+       // between the same two half-integers as p and rounding p is exact. 
When p
+       // is a half-integer, the sign of the product's rounding error decides.
+       pow := float64PowersOfTen256[scale+76]
+       if p := float64(v * pow); p < 1<<52 {
+               r := math.RoundToEven(p)
+               if p-r == 0.5 || r-p == 0.5 {
+                       if d := math.FMA(v, pow, -p); d > 0 {
+                               r = p + 0.5
+                       } else if d < 0 {
+                               r = p - 0.5
+                       }
+               }
+               return 0, uint64(r), true
+       }
+       m, e, ok := float64Parts(v)
+       if !ok {
+               return 0, 0, false
+       }
+       hi, lo = bits.Mul64(m, pow10U128[scale].lo)
+       hi += m * pow10U128[scale].hi
+       if e >= 0 {
+               n := 128 - bits.LeadingZeros64(hi)
+               if hi == 0 {
+                       n = 64 - bits.LeadingZeros64(lo)
+               }
+               if n+e > 127 {
+                       return 0, 0, false
+               }
+               if e >= 64 {
+                       return lo << (e - 64), 0, true
+               }
+               return hi<<e | lo>>(64-e), lo << e, true
+       }
+       k := -e
+       if k >= 128 {
+               // m*10^scale < 2^127, so the product is below 1/2.
+               return 0, 0, true
+       }
+       // half is the bit just below the units digit, sticky says whether any
+       // lower bit is set; then shift the fraction out.
+       var half, sticky bool
+       if j := k - 1; j >= 64 {
+               half = hi>>(j-64)&1 == 1
+               sticky = lo != 0 || hi&(1<<(j-64)-1) != 0
+       } else {
+               half = lo>>j&1 == 1
+               sticky = lo&(1<<j-1) != 0
+       }
+       if k >= 64 {
+               hi, lo = 0, hi>>(k-64)
+       } else {
+               hi, lo = hi>>k, lo>>k|hi<<(64-k)
+       }
+       if half && (sticky || lo&1 == 1) {
+               var carry uint64
+               lo, carry = bits.Add64(lo, 1, 0)
+               hi += carry
+       }
+       return hi, lo, true
+}
+
+// roundScaledFloat64Big returns v*mult rounded to the nearest integer, ties to
+// even, computed exactly from the binary value of a non-negative v. It returns
+// nil when v is not finite.
+func roundScaledFloat64Big(v float64, mult *big.Int) *big.Int {
+       m, e, ok := float64Parts(v)
+       if !ok {
+               return nil
+       }
+       c := new(big.Int).SetUint64(m)
+       c.Mul(c, mult)
+       if e >= 0 {
+               return c.Lsh(c, uint(e))
+       }
+       k := uint(-e)
+       half := c.Bit(int(k-1)) == 1
+       sticky := c.TrailingZeroBits() < k-1
+       c.Rsh(c, k)
+       if half && (sticky || c.Bit(0) == 1) {
+               c.Add(c, bigIntOne)
+       }
+       return c
+}
+
+var (
+       bigIntOne = big.NewInt(1)
+       // pow10U128 holds 10^i as 128-bit values.
+       pow10U128 = func() (t [23]struct{ hi, lo uint64 }) {
+               t[0].lo = 1
+               for i := 1; i < len(t); i++ {
+                       hi, lo := bits.Mul64(t[i-1].lo, 10)
+                       t[i].hi, t[i].lo = t[i-1].hi*10+hi, lo
+               }
+               return t
+       }()
+       // scaleMultipliersBig256 holds scaleMultipliers256 as big.Int values, 
built once.
+       scaleMultipliersBig256 = func() (out 
[len(scaleMultipliers256)]*big.Int) {
+               for i := range scaleMultipliers256 {
+                       out[i] = scaleMultipliers256[i].BigInt()
+               }
+               return out
+       }()
+)
+
 func fromPositiveFloat64_256(v float64, prec, scale int32) (Decimal256, error) 
{
+       // a negative precision keeps the float64 path below, as before
+       if scale >= 0 && scale <= int32(MaxScale[Decimal256]()) && prec >= 0 {
+               // Round the exact product v*10^scale to nearest even. 
Multiplying in
+               // float64 can lose coefficient digits before rounding.
+               if hi, lo, ok := roundScaledFloat64(v, scale); ok {
+                       // the result is below 2^127 < 10^39, so only prec <= 
38 can overflow

Review Comment:
   nit: this is correct, but it depends on `roundScaledFloat64` returning 
`ok=false` for anything that needs more than 127 bits. Could the comment say 
so, so the precondition doesn't get lost if that function changes?



##########
arrow/decimal128/decimal128.go:
##########
@@ -171,7 +171,157 @@ func scalePositiveFloat64(v float64, prec, scale int32) 
(float64, error) {
        return v, nil
 }
 
+// float64Parts splits a finite v into m*2^e with m < 2^53, ignoring the sign.
+func float64Parts(v float64) (m uint64, e int, ok bool) {
+       b := math.Float64bits(v)
+       m = b & (1<<52 - 1)
+       switch exp := int(b>>52) & 0x7ff; exp {
+       case 0x7ff:
+               return 0, 0, false
+       case 0:
+               return m, -1074, true
+       default:
+               return m | 1<<52, exp - 1075, true
+       }
+}
+
+// roundScaledFloat64 returns the exact product v*10^scale of a non-negative v,
+// rounded to the nearest integer with ties to even, as the 128-bit value 
hi:lo.
+// With v = m*2^e, m < 2^53 and 10^scale < 2^74 for scale <= 22, so m*10^scale
+// fits in 127 bits and is computed exactly, and no float64 rounding happens
+// before the final one. ok is false when scale > 22, v is not finite, or the
+// result needs more than 127 bits; the caller then needs the big.Int path.
+func roundScaledFloat64(v float64, scale int32) (hi, lo uint64, ok bool) {
+       if scale < 0 || scale > 22 {
+               return 0, 0, false
+       }
+       // 10^scale is exact in float64 here. Below 2^52 every half-integer is a
+       // float64, so unless p itself is one, the exact product lies strictly
+       // between the same two half-integers as p and rounding p is exact. 
When p
+       // is a half-integer, the sign of the product's rounding error decides.
+       pow := float64PowersOfTen[scale+38]
+       if p := float64(v * pow); p < 1<<52 {
+               r := math.RoundToEven(p)
+               if p-r == 0.5 || r-p == 0.5 {
+                       if d := math.FMA(v, pow, -p); d > 0 {
+                               r = p + 0.5
+                       } else if d < 0 {
+                               r = p - 0.5
+                       }
+               }
+               return 0, uint64(r), true
+       }
+       m, e, ok := float64Parts(v)
+       if !ok {
+               return 0, 0, false
+       }
+       hi, lo = bits.Mul64(m, pow10U128[scale].lo)
+       hi += m * pow10U128[scale].hi
+       if e >= 0 {
+               n := 128 - bits.LeadingZeros64(hi)
+               if hi == 0 {
+                       n = 64 - bits.LeadingZeros64(lo)
+               }
+               if n+e > 127 {
+                       return 0, 0, false
+               }
+               if e >= 64 {
+                       return lo << (e - 64), 0, true
+               }
+               return hi<<e | lo>>(64-e), lo << e, true
+       }
+       k := -e
+       if k >= 128 {
+               // m*10^scale < 2^127, so the product is below 1/2.
+               return 0, 0, true
+       }
+       // half is the bit just below the units digit, sticky says whether any
+       // lower bit is set; then shift the fraction out.
+       var half, sticky bool
+       if j := k - 1; j >= 64 {
+               half = hi>>(j-64)&1 == 1
+               sticky = lo != 0 || hi&(1<<(j-64)-1) != 0
+       } else {
+               half = lo>>j&1 == 1
+               sticky = lo&(1<<j-1) != 0
+       }
+       if k >= 64 {
+               hi, lo = 0, hi>>(k-64)
+       } else {
+               hi, lo = hi>>k, lo>>k|hi<<(64-k)
+       }
+       if half && (sticky || lo&1 == 1) {
+               var carry uint64
+               lo, carry = bits.Add64(lo, 1, 0)
+               hi += carry
+       }
+       return hi, lo, true
+}
+
+// roundScaledFloat64Big returns v*mult rounded to the nearest integer, ties to
+// even, computed exactly from the binary value of a non-negative v. It returns
+// nil when v is not finite.
+func roundScaledFloat64Big(v float64, mult *big.Int) *big.Int {
+       m, e, ok := float64Parts(v)
+       if !ok {
+               return nil
+       }
+       c := new(big.Int).SetUint64(m)
+       c.Mul(c, mult)
+       if e >= 0 {
+               return c.Lsh(c, uint(e))
+       }
+       k := uint(-e)
+       half := c.Bit(int(k-1)) == 1
+       sticky := c.TrailingZeroBits() < k-1
+       c.Rsh(c, k)
+       if half && (sticky || c.Bit(0) == 1) {
+               c.Add(c, bigIntOne)
+       }
+       return c
+}
+
+var (
+       bigIntOne = big.NewInt(1)
+       // pow10U128 holds 10^i as 128-bit values.
+       pow10U128 = func() (t [23]struct{ hi, lo uint64 }) {
+               t[0].lo = 1
+               for i := 1; i < len(t); i++ {
+                       hi, lo := bits.Mul64(t[i-1].lo, 10)
+                       t[i].hi, t[i].lo = t[i-1].hi*10+hi, lo
+               }
+               return t
+       }()
+       // scaleMultipliersBig holds scaleMultipliers as big.Int values, built 
once.
+       scaleMultipliersBig = func() (out [len(scaleMultipliers)]*big.Int) {
+               for i := range scaleMultipliers {
+                       out[i] = scaleMultipliers[i].BigInt()
+               }
+               return out
+       }()
+)
+
 func fromPositiveFloat64(v float64, prec, scale int32) (Num, error) {
+       // a negative precision keeps the float64 path below, as before
+       if scale >= 0 && scale <= MaxScale && prec >= 0 {
+               // Round the exact product v*10^scale to nearest even. 
Multiplying in
+               // float64 can lose coefficient digits before rounding.
+               if hi, lo, ok := roundScaledFloat64(v, scale); ok {
+                       if pm := scaleMultipliers[prec]; hi > uint64(pm.hi) || 
(hi == uint64(pm.hi) && lo >= pm.lo) {
+                               return Num{}, fmt.Errorf("cannot convert %f to 
decimal128(precision=%d, scale=%d): overflow", v, prec, scale)
+                       }
+                       return Num{hi: int64(hi), lo: lo}, nil
+               }
+               coefficient := roundScaledFloat64Big(v, 
scaleMultipliersBig[scale])

Review Comment:
   Above scale 22 this path allocates 3 times per value. Locally 
Decimal128(38,30) goes from 5.15k to 48.0k ns/op per 1024 values, and 
Decimal256(76,30) from 15.7k to 54.1k.
   
   For decimal128 the product doesn't need `big.Int`. With m < 2^53 and 10^38 < 
2^127 it fits in 180 bits, so a three-limb fixed-width multiply with the same 
half/sticky rounding as `roundScaledFloat64` would keep every decimal128 scale 
allocation-free. `big.Int` would then only be needed for decimal256 scales 
above 38.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to