fixed

package module
v0.2.0-alpha Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 31, 2026 License: MIT Imports: 2 Imported by: 0

README

fixed

fixed is a small Go package for signed Q32.32 arithmetic. Equal inputs produce the same result bits on every supported architecture.

A Q value uses one int64: 32 bits for the signed integer part and 32 bits for the fraction. This gives a resolution of 2⁻³² and a range from -2³¹ to 2³¹ - 2⁻³².

The module is pre-v1. Its import path may change before the first stable release. It requires Go 1.26.4 or newer.

Install

go get github.com/dhannyell/fixed

Quick start

package main

import (
	"fmt"

	"github.com/dhannyell/fixed"
)

func main() {
	a := fixed.Vec2{X: fixed.FromInt(1), Y: fixed.FromInt(2)}
	b := fixed.Vec2{X: fixed.FromInt(4), Y: fixed.FromInt(6)}
	distance := a.Distance(b)

	quarterTurn := fixed.RotFromTurns(fixed.FromRatio(1, 4))
	direction := quarterTurn.Apply(fixed.Vec2{X: fixed.One()})

	fmt.Println(distance)                 // 5
	fmt.Println(direction.X, direction.Y) // 0 1
}

Why there is no float constructor

Floating-point input can already contain small differences caused by an earlier computation. The package cannot recover the intended exact value from those bits. For this reason, fixed accepts only explicit inputs:

  • FromInt for integers.
  • FromRatio for exact ratios.
  • MustParse for decimal literals.
  • FromRaw for an exact Q32.32 bit pattern.

String provides the inverse text boundary. It emits a canonical decimal representation, and every value satisfies:

fixed.MustParse(q.String()) == q

Arithmetic contract

The package uses one explicit rule for each operation:

Operation Result
Add, Sub Exact Q32.32 result, with saturation on overflow
Mul Product floored to Q32.32, with saturation on overflow
Div, FromRatio Quotient truncated toward zero, with saturation on overflow
Sqrt Square root floored to Q32.32
Round, MustParse Nearest representable value; exact halves round away from zero

Division by zero panics. Sqrt of a negative value also panics.

Saturated addition is not associative near the limits. Reordering a sum can therefore change its result. Accumulators should have enough headroom to avoid saturation.

Every saturation increments a process-wide atomic counter. SaturationCount provides diagnostics without changing any Q value or operation result.

Vectors and angles

Vec2 provides the usual 2D operations over Q: addition, scaling, dot product, length, normalization, distance, and interpolation. LenSq follows the scalar operation order and can saturate even when the length still fits. Len uses a 128-bit intermediate and saturates only when the final magnitude does not fit. Normalize scales the components before squaring them, which avoids intermediate overflow and underflow.

Angles use turns instead of radians. One() is one complete revolution, Half() is half a revolution, and FromRatio(1, 4) is a quarter turn. This maps the fractional bits of Q directly onto the circle and avoids reduction through an approximation of pi.

SinTurns, CosTurns, and Atan2Turns use committed lookup tables and linear interpolation. Their maximum absolute error is 2⁻²⁰. Rot stores a rotation as its sine and cosine, which makes application, composition, and inversion available without another trigonometric lookup. The zero value of Rot is not a valid rotation; start with RotIdentity or RotFromTurns.

Architecture

fixed is a leaf module. The package imports only math/bits and sync/atomic. This small dependency surface lets applications use the numeric type without importing unrelated systems.

The Q type is opaque. Constructors control how values enter the package, operations own saturation and rounding, and Raw is the boundary for exact bit access.

The module is one flat package by design. Every public type shares one contract, so subpackages would only split the documentation and add import noise. File names carry the layers: q*/decimal* for the scalar, vec2* and rot* for the plane, trig* for the kernel. Directories exist only for content outside the package interface: internal/ for tools and .github/ for CI.

The Go implementation defines the bit-level contract. An independent implementation must preserve the rounding, saturation, and raw representation before it exchanges values with this package. A change to one of these rules is a semantic change, not an internal refactor.

Development

Run the standard checks before submitting a change:

go test ./...
go vet ./...
golangci-lint run ./...

See the package documentation for the API reference and the full behavioral contract.

License

fixed is available under the MIT License.

Documentation

Overview

Package fixed implements deterministic Q32.32 fixed-point arithmetic.

Q stores one signed value in an int64. The high 32 bits contain the signed integer part. The low 32 bits contain the fraction. The resolution is 2⁻³². The range is [-2³¹, 2³¹ - 2⁻³²]. Each operation produces the same bits on every supported architecture.

Overflow

An overflow saturates to MinValue or MaxValue. SaturationCount reports saturation events for diagnostics. The counter does not affect Q values or operation results.

Q.Div panics for a zero divisor. FromRatio panics for a zero denominator. Q.Sqrt panics for a negative input.

Saturated addition is not associative near the range limits. Do not reorder an accumulation. Use enough numeric headroom to prevent saturation.

Rounding

Q.Mul floors the 128-bit product when it converts the result to Q32.32. This operation matches an arithmetic right shift. Q.Div and FromRatio truncate toward zero. Q.Sqrt floors its result.

Q.Round and MustParse round to the nearest representable value. An exact half rounds away from zero.

Construction and text

Q is opaque. Construct values with FromInt, FromRatio, MustParse, or FromRaw. The package does not accept float values because a computed float can contain architecture-dependent bits.

Q.String returns the exact canonical decimal form. For every q, MustParse(q.String()) == q.

Angles

Angles use turns. One is a full revolution. The fractional bits of a Q map directly to the circle, so range reduction does not use pi and does not round.

SinTurns and CosTurns accept every Q value. They never panic or saturate, and their results stay in [-One, One]. They use a 1024-interval quarter-wave table. Table entries round to nearest, and linear interpolation floors. The maximum absolute error is 2⁻²⁰.

Atan2Turns returns an angle in (-1/2, 1/2] turns. It reduces the input to a ratio in [0, 1], truncates that ratio to Q32.32, and uses a 1024-interval table. Table entries round to nearest, and linear interpolation floors. Octant reconstruction is exact.

Vectors and rotations

Vec2.LenSq composes scalar multiplication and addition, so it can saturate even when the length fits in Q32.32. Vec2.Len computes the length with a 128-bit intermediate and saturates only when the final length is out of range. Vec2.Normalize scales the components before it squares them, so intermediate underflow cannot turn a nonzero vector into the zero vector.

Rot stores a rotation as its sine and cosine. The zero Rot is invalid. Use RotIdentity or RotFromTurns to construct a rotation. Repeated composition can introduce rounding drift; Rot.Normalize restores unit length.

Compatibility contract

The raw representation, saturation rules, and rounding rules are part of the public contract. An independent implementation must reproduce these rules before it exchanges raw values with this package. The trigonometric raw outputs are also part of the contract. A compatible implementation may use a different representation, but it must produce the same output bits.

Dependencies

The fixed package imports only math/bits and sync/atomic.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func ResetSaturationCount

func ResetSaturationCount()

ResetSaturationCount zeroes the saturation counter.

func SaturationCount

func SaturationCount() uint64

SaturationCount reports the number of saturation events since the last reset.

Types

type Q

type Q struct {
	// contains filtered or unexported fields
}

Q stores an opaque signed Q32.32 value. Its zero value is 0.

func Atan2Turns added in v0.2.1

func Atan2Turns(y, x Q) Q

Atan2Turns returns the angle of (x, y) in (-1/2, 1/2] turns. Atan2Turns(Zero(), Zero()) returns Zero. It never panics or saturates. The unit ratio is truncated to Q32.32, table entries round to nearest, and linear interpolation floors. The maximum absolute error is 2⁻²⁰ turn.

func CosTurns added in v0.2.1

func CosTurns(t Q) Q

CosTurns returns the cosine of t in turns. It uses the same rules as SinTurns with a quarter-turn shift.

func FromInt

func FromInt(i int) Q

FromInt returns i as a Q value. It saturates outside [-2³¹, 2³¹-1].

Example
package main

import (
	"fmt"

	"github.com/dhannyell/fixed"
)

func main() {
	fmt.Println(fixed.FromInt(3))
	fmt.Println(fixed.FromInt(-2))
}
Output:
3
-2

func FromRatio

func FromRatio(num, den int) Q

FromRatio returns num/den truncated toward zero. It saturates on overflow. It panics when den is zero.

Example
package main

import (
	"fmt"

	"github.com/dhannyell/fixed"
)

func main() {
	// Use a ratio for exact fractional constants. There is no FromFloat.
	q := fixed.FromRatio(5, 2)
	fmt.Println(q)
}
Output:
2.5

func FromRaw

func FromRaw(raw int64) Q

FromRaw returns the Q value with the specified signed bit pattern.

func Half

func Half() Q

Half returns the fixed-point value 1/2.

func MaxValue

func MaxValue() Q

MaxValue returns the largest representable Q value, 2³¹ - 2⁻³².

func MinValue

func MinValue() Q

MinValue returns the smallest representable Q value, -2³¹.

func MustParse

func MustParse(s string) Q

MustParse parses a decimal literal. It rounds to the nearest Q value, with exact halves away from zero. It saturates outside the Q range and panics on malformed input.

Example
package main

import (
	"fmt"

	"github.com/dhannyell/fixed"
)

func main() {
	fmt.Println(fixed.MustParse("6.25"))
	fmt.Println(fixed.MustParse("-0.001"))
}
Output:
6.25
-0.00099999993108212947845458984375

func One

func One() Q

One returns the fixed-point value 1.

func SinTurns added in v0.2.1

func SinTurns(t Q) Q

SinTurns returns the sine of t, where One is a full revolution. It uses only the fractional part of t, accepts every Q value, and returns a value in [-One, One] without saturation.

The 1024-interval quarter-wave table rounds entries to nearest. Linear interpolation floors. The maximum absolute error is 2⁻²⁰.

func Zero

func Zero() Q

Zero returns the fixed-point value 0.

func (Q) Abs

func (q Q) Abs() Q

Abs returns the magnitude of q. Abs of MinValue saturates to MaxValue.

func (Q) Add

func (q Q) Add(o Q) Q

Add returns q+o. It saturates on overflow.

func (Q) Ceil

func (q Q) Ceil() Q

Ceil returns the smallest integer multiple of One that is not below q. It saturates when the result is outside the Q range.

func (Q) Clamp

func (q Q) Clamp(lo, hi Q) Q

Clamp returns q limited to [lo, hi]. It requires lo <= hi.

Example
package main

import (
	"fmt"

	"github.com/dhannyell/fixed"
)

func main() {
	speed := fixed.FromInt(150)
	limited := speed.Clamp(fixed.Zero(), fixed.FromInt(100))
	fmt.Println(limited)
}
Output:
100

func (Q) Cmp

func (q Q) Cmp(o Q) int

Cmp returns -1 when q < o, 0 when q == o, and 1 when q > o.

func (Q) Div

func (q Q) Div(o Q) Q

Div returns q/o truncated toward zero. It saturates on overflow. It panics when o is zero.

func (Q) Eq

func (q Q) Eq(o Q) bool

Eq reports whether q == o.

func (Q) Floor

func (q Q) Floor() Q

Floor returns the largest integer multiple of One not above q.

func (Q) Int

func (q Q) Int() int

Int returns the integer part truncated toward zero.

func (Q) Less

func (q Q) Less(o Q) bool

Less reports whether q < o.

func (Q) Max

func (q Q) Max(o Q) Q

Max returns the larger of q and o.

func (Q) Min

func (q Q) Min(o Q) Q

Min returns the smaller of q and o.

func (Q) Mul

func (q Q) Mul(o Q) Q

Mul returns q*o. It floors the product to Q32.32 and saturates on overflow.

Example
package main

import (
	"fmt"

	"github.com/dhannyell/fixed"
)

func main() {
	area := fixed.FromRatio(5, 2).Mul(fixed.FromInt(4))
	fmt.Println(area)
}
Output:
10

func (Q) Neg

func (q Q) Neg() Q

Neg returns -q. Neg of MinValue saturates to MaxValue.

func (Q) Raw

func (q Q) Raw() int64

Raw returns the signed Q32.32 bit pattern of q.

func (Q) Round

func (q Q) Round() Q

Round returns the nearest integer multiple of One. An exact half rounds away from zero. Round saturates when the result is outside the Q range.

func (Q) Sqrt

func (q Q) Sqrt() Q

Sqrt returns floor(sqrt(q)). It panics when q is negative. The result cannot overflow.

func (Q) String

func (q Q) String() string

String returns the exact canonical decimal form of q, such as "-6.25". For every q, MustParse(q.String()) == q. Use Raw for the exact bit pattern.

Example
package main

import (
	"fmt"

	"github.com/dhannyell/fixed"
)

func main() {
	q := fixed.FromRaw(1)
	text := q.String()
	fmt.Println(text)
	fmt.Println(fixed.MustParse(text).Eq(q))
}
Output:
0.00000000023283064365386962890625
true

func (Q) Sub

func (q Q) Sub(o Q) Q

Sub returns q-o. It saturates on overflow.

type Rot added in v0.2.1

type Rot struct {
	Sin, Cos Q
}

Rot is a 2D rotation stored as its sine and cosine.

The zero Rot is not a valid rotation; start from RotIdentity or RotFromTurns.

func RotFromTurns added in v0.2.1

func RotFromTurns(t Q) Rot

RotFromTurns returns the rotation by the angle t in turns. It shares the kernel and the contract of SinTurns and CosTurns.

Example
package main

import (
	"fmt"

	"github.com/dhannyell/fixed"
)

func main() {
	// A quarter turn sends (1, 0) to (0, 1) exactly.
	r := fixed.RotFromTurns(fixed.FromRatio(1, 4))
	v := r.Apply(fixed.Vec2{X: fixed.One(), Y: fixed.Zero()})
	fmt.Println(v.X, v.Y)
}
Output:
0 1

func RotIdentity added in v0.2.1

func RotIdentity() Rot

RotIdentity returns the rotation by zero turns.

func (Rot) Apply added in v0.2.1

func (r Rot) Apply(v Vec2) Vec2

Apply rotates the vector v by r.

func (Rot) Inv added in v0.2.1

func (r Rot) Inv() Rot

Inv returns the inverse rotation. For a unit rotation the inverse is the conjugate, so no division is needed.

func (Rot) Mul added in v0.2.1

func (r Rot) Mul(o Rot) Rot

Mul composes the rotations: the result rotates by r then by o. It uses the angle-sum identities, so each product floors once.

func (Rot) Normalize added in v0.2.1

func (r Rot) Normalize() Rot

Normalize rescales r to unit length. A zero r returns the identity.

type Vec2 added in v0.2.1

type Vec2 struct {
	X, Y Q
}

Vec2 is a 2D vector of Q components.

func (Vec2) Add added in v0.2.1

func (v Vec2) Add(o Vec2) Vec2

Add returns the sum of two vectors.

func (Vec2) Distance added in v0.2.1

func (v Vec2) Distance(o Vec2) Q

Distance returns the distance between v and o.

func (Vec2) DistanceSq added in v0.2.1

func (v Vec2) DistanceSq(o Vec2) Q

DistanceSq returns the squared distance between v and o.

func (Vec2) Div added in v0.2.1

func (v Vec2) Div(s Q) Vec2

Div returns v divided by s. It panics when s is zero.

func (Vec2) Dot added in v0.2.1

func (v Vec2) Dot(o Vec2) Q

Dot returns the dot product of two vectors.

func (Vec2) Len added in v0.2.1

func (v Vec2) Len() Q

Len returns the length of the vector, floored to the Q32.32 grid.

func (Vec2) LenSq added in v0.2.1

func (v Vec2) LenSq() Q

LenSq returns the squared length of the vector. It uses the scalar multiplication and addition rules, including saturation.

func (Vec2) Lerp added in v0.2.1

func (v Vec2) Lerp(target Vec2, t Q) Vec2

Lerp linearly interpolates between v and target by t. t is not clamped.

func (Vec2) Mul added in v0.2.1

func (v Vec2) Mul(s Q) Vec2

Mul returns v scaled by s.

func (Vec2) Normalize added in v0.2.1

func (v Vec2) Normalize() Vec2

Normalize returns a unit vector with the same direction as v. The zero vector returns the zero vector.

Example
package main

import (
	"fmt"

	"github.com/dhannyell/fixed"
)

func main() {
	v := fixed.Vec2{X: fixed.Zero(), Y: fixed.FromInt(-7)}
	u := v.Normalize()
	fmt.Println(u.X, u.Y)
}
Output:
0 -1

func (Vec2) Sub added in v0.2.1

func (v Vec2) Sub(o Vec2) Vec2

Sub returns the difference between two vectors.

Directories

Path Synopsis
internal
gentable command
Command gentable writes the lookup tables used by the trigonometric functions.
Command gentable writes the lookup tables used by the trigonometric functions.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL