Add kahanSumInc and kahanSumDec helper functions

Signed-off-by: Aleksandr Smirnov <5targazer@mail.ru>
This commit is contained in:
Aleksandr Smirnov 2024-12-17 19:24:57 +03:00
parent dd95a7e231
commit 14f3403447

View file

@ -410,6 +410,38 @@ func (h *FloatHistogram) Add(other *FloatHistogram) (*FloatHistogram, error) {
return h, nil
}
// kahanSumInc performs addition of two floating-point numbers using the Kahan summation algorithm.
func kahanSumInc(inc, sum, c float64) (newSum, newC float64) {
t := sum + inc
switch {
case math.IsInf(t, 0):
c = 0
// Using Neumaier improvement, swap if next term larger than sum.
case math.Abs(sum) >= math.Abs(inc):
c += (sum - t) + inc
default:
c += (inc - t) + sum
}
return t, c
}
// kahanSumDec performs subtraction of one floating-point number from another using the Kahan summation algorithm.
func kahanSumDec(dec, sum, c float64) (newSum, newC float64) {
t := sum - dec
switch {
case math.IsInf(t, 0):
c = 0
// Using Neumaier improvement, swap if next term larger than sum.
case math.Abs(sum) >= math.Abs(dec):
c += (sum - t) - dec
default:
c += (-dec - t) + sum
}
return t, c
}
// Sub works like Add but subtracts the other histogram.
func (h *FloatHistogram) Sub(other *FloatHistogram) (*FloatHistogram, error) {
if h.UsesCustomBuckets() != other.UsesCustomBuckets() {