File: fixedpoint.go

package info (click to toggle)
golang-github-mesos-mesos-go 0.0.6%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, forky, sid, trixie
  • size: 11,724 kB
  • sloc: makefile: 163
file content (35 lines) | stat: -rw-r--r-- 1,122 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package mesos

// fixed point scalar math from mesos:src/common/values.cpp
// --
// We manipulate scalar values by converting them from floating point to a
// fixed point representation, doing a calculation, and then converting
// the result back to floating point. We deliberately only preserve three
// decimal digits of precision in the fixed point representation. This
// ensures that client applications see predictable numerical behavior, at
// the expense of sacrificing some precision.

import "math"

func convertToFloat64(f int64) float64 {
	// NOTE: We do the conversion from fixed point via integer division
	// and then modulus, rather than a single floating point division.
	// This ensures that we only apply floating point division to inputs
	// in the range [0,999], which is easier to check for correctness.
	var (
		quotient  = float64(f / 1000)
		remainder = float64(f%1000) / 1000.0
	)
	return quotient + remainder
}

func convertToFixed64(f float64) int64 {
	return round64(f * 1000)
}

func round64(f float64) int64 {
	if math.Abs(f) < 0.5 {
		return 0
	}
	return int64(f + math.Copysign(0.5, f))
}