Table of Contents

Class FixedMath

Namespace
FixedMathSharp
Assembly
FixedMathSharp.dll

A static class that provides a variety of fixed-point math functions. Fixed-point numbers are represented as Fixed64.

public static class FixedMath
Inheritance
FixedMath
Inherited Members

Fields

DEFAULT_TOLERANCE_L

Default tolerance for fuzzy comparisons. Approximately 2^-24 (~5.96e-8) in value space.

public const long DEFAULT_TOLERANCE_L = 256

Field Value

long

MASK_UL

Represents a bitmask with all bits set except for the lowest SHIFT_AMOUNT_I bits.

public const ulong MASK_UL = 18446744069414584320

Field Value

ulong

Remarks

This constant is typically used to isolate or clear the lower SHIFT_AMOUNT_I bits of an unsigned 64-bit value. The value of SHIFT_AMOUNT_I determines how many least significant bits are masked out.

MAX_SHIFTED_AMOUNT_UI

Represents the maximum value that can be produced by left-shifting 1 by SHIFT_AMOUNT_I bits and subtracting 1.

public const uint MAX_SHIFTED_AMOUNT_UI = 4294967295

Field Value

uint

Remarks

This constant is typically used as a bitmask to extract or limit values to the range defined by SHIFT_AMOUNT_I. The value is always non-negative and fits within a 32-bit unsigned integer.

MAX_VALUE_L

Represents the largest possible value for a 64-bit fixed-point number.

public const long MAX_VALUE_L = 9223372036854775807

Field Value

long

Remarks

Use this constant to perform comparisons or to initialize variables that require the maximum representable value for a 64-bit fixed-point type.

MIN_INCREMENT_L

The smallest non-zero raw increment representable by Fixed64.

public const long MIN_INCREMENT_L = 1

Field Value

long

MIN_VALUE_L

Represents the smallest possible value for a 64-bit fixed-point number.

public const long MIN_VALUE_L = -9223372036854775808

Field Value

long

Remarks

Use this constant to check for underflow conditions or to initialize variables that require the minimum representable value for a 64-bit fixed-point type.

ONE_L

Represents the value 1 shifted left by the number of bits specified by SHIFT_AMOUNT_I.

public const long ONE_L = 4294967296

Field Value

long

SCALE_FACTOR_D

Represents the precomputed scale factor used for double-precision calculations.

public const double SCALE_FACTOR_D = 2.3283064365386963E-10

Field Value

double

Remarks

This constant is intended only for converting fixed-point values to double-precision representations in performance-critical scenarios.

SCALE_FACTOR_F

Represents the precomputed scale factor used for floating-point calculations.

public const float SCALE_FACTOR_F = 2.3283064E-10

Field Value

float

Remarks

This constant is intended only for converting fixed-point values to floating-point representations in performance-critical scenarios.

SCALE_FACTOR_M

Represents the precomputed scale factor used for decimal calculations.

public const readonly decimal SCALE_FACTOR_M = 0.0000000002328306436538696289

Field Value

decimal

Remarks

This constant is intended only for converting fixed-point values to decimal representations in performance-critical scenarios.

SHIFT_AMOUNT_I

Represents the number of bits to shift for fixed-point representation.

public const int SHIFT_AMOUNT_I = 32

Field Value

int

Properties

CanonicalSinCosErrorBound

Gets the conservative absolute approximation-error bound for Sin(Fixed64) and Cos(Fixed64) when the input is already canonical in [-π, π].

public static Fixed64 CanonicalSinCosErrorBound { get; }

Property Value

Fixed64

Remarks

The bound includes the degree-8 cosine remainder on [0, π/4], coefficient quantization, fixed-point Horner rounding, and the tuned sine approximation error. Raw-neighborhood and principal-range tests validate range-reduction seams independently of exact anchors.

This bound does not include phase error accumulated while reducing a large multi-turn input by the fixed-point approximation of 2π. A consumer propagating a strict error budget must canonicalize its angle before turns accumulate or account for that phase error too.

Consumers that propagate sine/cosine error through rotations must also account for their own multiply, add, and normalization error.

Pow10Lookup

Provides a lookup table of integer powers of 10 from 10^0 to 10^9.

public static ReadOnlySpan<int> Pow10Lookup { get; }

Property Value

ReadOnlySpan<int>

Remarks

This array can be used to efficiently retrieve the value of 10 raised to an integer exponent within the supported range, avoiding repeated calculations. The index corresponds to the exponent.

Methods

Abs(Fixed64)

Returns the absolute value of a Fixed64 number.

public static Fixed64 Abs(Fixed64 value)

Parameters

value Fixed64

Returns

Fixed64

Acos(Fixed64)

Returns the arccosine of the specified number x, calculated using a combination of the atan and sqrt functions.

public static Fixed64 Acos(Fixed64 x)

Parameters

x Fixed64

The input value whose arccosine is to be computed. Should be in the range [-1, 1].

Returns

Fixed64

The arccosine of x in radians.

Exceptions

ArgumentOutOfRangeException

Thrown if x is outside the domain [-1, 1].

Asin(Fixed64)

Returns the arc-sine of a fixed-point number x, which is the angle in radians whose sine is x, using a combination of a Taylor series expansion and trigonometric identities.

For values of x near ±1, the identity asin(x) = π/2 - acos(x) is used for stability. For values of x near 0, a Taylor series expansion is used.

public static Fixed64 Asin(Fixed64 x)

Parameters

x Fixed64

The input value (sine) whose arcsine is to be computed. Should be in the range [-1, 1].

Returns

Fixed64

The arc-sine of x in radians.

Exceptions

ArithmeticException

Thrown if x is outside the domain [-1, 1].

Atan(Fixed64)

Returns the arctangent of the specified number, using a more accurate approximation for larger values. This function has at least 7 decimals of accuracy.

public static Fixed64 Atan(Fixed64 z)

Parameters

z Fixed64

Returns

Fixed64

Atan2(Fixed64, Fixed64)

Computes the angle whose tangent is the quotient of two specified numbers.

public static Fixed64 Atan2(Fixed64 y, Fixed64 x)

Parameters

y Fixed64

The y-coordinate of the point to which the angle is measured.

x Fixed64

The x-coordinate of the point to which the angle is measured.

Returns

Fixed64

An angle, θ, measured in radians, such that -π ≤ θ ≤ π, and tan(θ) = y / x, taking into account the quadrants of the inputs to determine the sign of the result.

Remarks

Uses a fixed-point arithmetic approximation for the arc tangent function, which is more efficient than using floating-point arithmetic, especially on systems where floating-point operations are expensive.

Average(Fixed64, Fixed64, Fixed64)

Returns the arithmetic average of three fixed-point values without intermediate overflow.

public static Fixed64 Average(Fixed64 first, Fixed64 second, Fixed64 third)

Parameters

first Fixed64
second Fixed64
third Fixed64

Returns

Fixed64

Remarks

The exact raw Q32.32 sum is divided by three and rounded to the nearest raw value.

BarycentricCoordinate(Fixed64, Fixed64, Fixed64, Fixed64, Fixed64)

Performs barycentric interpolation between three scalar coordinates from a triangle.

public static Fixed64 BarycentricCoordinate(Fixed64 coordA, Fixed64 coordB, Fixed64 coordC, Fixed64 weightB, Fixed64 weightC)

Parameters

coordA Fixed64

The coordinate of the first vertex.

coordB Fixed64

The coordinate of the second vertex.

coordC Fixed64

The coordinate of the third vertex.

weightB Fixed64

The barycentric weight for the second vertex.

weightC Fixed64

The barycentric weight for the third vertex.

Returns

Fixed64

The interpolated scalar coordinate.

Remarks

Endpoint differences, both weighted terms, and the base coordinate are accumulated before one final round-half-to-even conversion. Results outside the Fixed64 range saturate.

CatmullRom(Fixed64, Fixed64, Fixed64, Fixed64, Fixed64)

Computes the interpolated point along a Catmull-Rom spline given four control points.

public static Fixed64 CatmullRom(Fixed64 p0, Fixed64 p1, Fixed64 p2, Fixed64 p3, Fixed64 t)

Parameters

p0 Fixed64

The first control point.

p1 Fixed64

The second control point.

p2 Fixed64

The third control point.

p3 Fixed64

The fourth control point.

t Fixed64

Interpolation factor between 0 and 1.

Returns

Fixed64

The interpolated point on the spline.

Ceil(Fixed64)

Returns the smallest integral value that is greater than or equal to the specified number.

public static Fixed64 Ceil(Fixed64 value)

Parameters

value Fixed64

Returns

Fixed64

Clamp(Fixed64, Fixed64, Fixed64)

Clamps a fixed-point value between the given minimum and maximum values.

public static Fixed64 Clamp(Fixed64 f1, Fixed64 min, Fixed64 max)

Parameters

f1 Fixed64
min Fixed64
max Fixed64

Returns

Fixed64

Clamp01(Fixed64)

Clamps value between 0 and 1 and returns value.

public static Fixed64 Clamp01(Fixed64 value)

Parameters

value Fixed64

Returns

Fixed64

ClampOne(Fixed64)

Clamps the value between -1 and 1 inclusive.

public static Fixed64 ClampOne(Fixed64 f1)

Parameters

f1 Fixed64

The Fixed64 value to clamp.

Returns

Fixed64

Returns a value clamped between -1 and 1.

Clamp<T>(T, T, T)

Clamps a value to the inclusive range [min, max].

public static T Clamp<T>(T value, T min, T max) where T : IComparable<T>

Parameters

value T

The value to clamp.

min T

The minimum allowed value.

max T

The maximum allowed value.

Returns

T

The clamped value.

Type Parameters

T

The type of the value, must implement IComparable<T>.

CopySign(Fixed64, Fixed64)

Produces a value with the magnitude of the first argument and the sign of the second argument.

public static Fixed64 CopySign(Fixed64 x, Fixed64 y)

Parameters

x Fixed64
y Fixed64

Returns

Fixed64

Cos(Fixed64)

Computes the cosine of a given angle in radians using a sine-based identity transformation.

public static Fixed64 Cos(Fixed64 x)

Parameters

x Fixed64

The angle in radians.

Returns

Fixed64

The cosine of the given angle, in fixed-point format.

Remarks

  • Instead of directly approximating cosine, this function derives cos(x) using the identity cos(x) = sin(x + π/2).
  • The underlying sine function uses complementary reduced-range sine and cosine polynomials so quadrant anchors remain continuous.
  • The function automatically normalizes input values to the range [-π, π] for stability.

CubicInterpolate(Fixed64, Fixed64, Fixed64, Fixed64, Fixed64)

Performs cubic interpolation between two points with tangents at those points.

public static Fixed64 CubicInterpolate(Fixed64 p0, Fixed64 p1, Fixed64 m0, Fixed64 m1, Fixed64 t)

Parameters

p0 Fixed64

The first point.

p1 Fixed64

The second point.

m0 Fixed64

The tangent at p0.

m1 Fixed64

The tangent at p1.

t Fixed64

A value between 0 and 1 that represents the interpolation factor.

Returns

Fixed64

The interpolated value between p0 and p1.

DegToRad(Fixed64)

Converts a value in degrees to radians.

public static Fixed64 DegToRad(Fixed64 deg)

Parameters

deg Fixed64

Returns

Fixed64

FastAdd(Fixed64, Fixed64)

Adds two fixed-point numbers by adding their raw Q32.32 payloads without saturation.

public static Fixed64 FastAdd(Fixed64 x, Fixed64 y)

Parameters

x Fixed64
y Fixed64

Returns

Fixed64

Remarks

This is an unchecked hot-path helper. Use it only when the raw sum is known to fit in long or raw wraparound is an intentional part of the algorithm. Use operator +(Fixed64, Fixed64) for the public saturating add contract.

FastDiv(Fixed64, Fixed64)

Divides two fixed-point numbers with an optimized path for known-positive divisors.

public static Fixed64 FastDiv(Fixed64 x, Fixed64 y)

Parameters

x Fixed64
y Fixed64

Returns

Fixed64

Remarks

This helper preserves the same deterministic rounding, divide-by-zero, and saturation semantics as operator /(Fixed64, Fixed64). The fast path is only used when y is positive; non-positive divisors fall back to the guarded division operator. Prefer the operator unless the divisor positivity invariant is already proven by the caller.

FastMod(Fixed64, Fixed64)

Computes the raw remainder of two fixed-point numbers without special-case guards.

public static Fixed64 FastMod(Fixed64 x, Fixed64 y)

Parameters

x Fixed64
y Fixed64

Returns

Fixed64

Remarks

This is an unchecked hot-path helper. It delegates directly to the raw long remainder operation, so raw zero divisors and integer edge cases follow runtime integer remainder behavior. Use operator %(Fixed64, Fixed64) for the public guarded remainder contract.

FastMul(Fixed64, Fixed64)

Multiplies two fixed-point numbers using unchecked Q32.32 partial products.

public static Fixed64 FastMul(Fixed64 x, Fixed64 y)

Parameters

x Fixed64
y Fixed64

Returns

Fixed64

Remarks

This is an unchecked hot-path helper. It skips the full-width overflow/saturation path used by operator *(Fixed64, Fixed64) and truncates discarded fractional bits instead of applying the operator's round-half-to-even behavior. Use it only when inputs are constrained and that precision tradeoff is acceptable. Integral operands take a direct raw multiplication path.

FastSub(Fixed64, Fixed64)

Subtracts two fixed-point numbers by subtracting their raw Q32.32 payloads without saturation.

public static Fixed64 FastSub(Fixed64 x, Fixed64 y)

Parameters

x Fixed64
y Fixed64

Returns

Fixed64

Remarks

This is an unchecked hot-path helper. Use it only when the raw difference is known to fit in long or raw wraparound is an intentional part of the algorithm. Use operator -(Fixed64, Fixed64) for the public saturating subtract contract.

Floor(Fixed64)

Returns the largest integer less than or equal to the specified number (floor function). Efficiently zeroes out the fractional part.

public static Fixed64 Floor(Fixed64 value)

Parameters

value Fixed64

Returns

Fixed64

GetHypotenuse(Fixed64, Fixed64)

Calculates the hypotenuse of a right triangle given sides a and b using the Pythagorean theorem: sqrt(a^2 + b^2).

public static Fixed64 GetHypotenuse(Fixed64 a, Fixed64 b)

Parameters

a Fixed64

The length of side a.

b Fixed64

The length of side b.

Returns

Fixed64

The length of the hypotenuse.

HermiteSpline(Fixed64, Fixed64, Fixed64, Fixed64, Fixed64)

Performs a Hermite interpolation between two Fixed64 values, using the specified tangents and interpolation amount.

public static Fixed64 HermiteSpline(Fixed64 value1, Fixed64 tangent1, Fixed64 value2, Fixed64 tangent2, Fixed64 amount)

Parameters

value1 Fixed64

The first value.

tangent1 Fixed64

The tangent at the first value.

value2 Fixed64

The second value.

tangent2 Fixed64

The tangent at the second value.

amount Fixed64

The interpolation amount.

Returns

Fixed64

The Hermite spline interpolated value.

Lerp(Fixed64, Fixed64, Fixed64)

Linearly interpolates between two fixed-point values based on a given interpolation factor.

public static Fixed64 Lerp(Fixed64 from, Fixed64 to, Fixed64 t)

Parameters

from Fixed64

The starting value.

to Fixed64

The ending value.

t Fixed64

A value between 0 and 1 that represents the interpolation factor.

Returns

Fixed64

The interpolated value between from and to.

Remarks

The interpolation is clamped between from and to based on the value of t. If t is less than 0, the result is from. If t is greater than 1, the result is to.

Ln(Fixed64)

Returns the natural logarithm of a specified fixed-point number. Provides at least 7 decimals of accuracy.

public static Fixed64 Ln(Fixed64 x)

Parameters

x Fixed64

Returns

Fixed64

Log2(Fixed64)

Returns the base-2 logarithm of a specified number. Provides at least 9 decimals of accuracy.

public static Fixed64 Log2(Fixed64 x)

Parameters

x Fixed64

Returns

Fixed64

Remarks

This implementation is based on Clay. S. Turner's fast binary logarithm algorithm (C. S. Turner, "A Fast Binary Logarithm Algorithm", IEEE Signal Processing Mag., pp. 124,140, Sep. 2010.)

Max(Fixed64, Fixed64)

Returns the larger of two fixed-point values.

public static Fixed64 Max(Fixed64 a, Fixed64 b)

Parameters

a Fixed64
b Fixed64

Returns

Fixed64

Midpoint(Fixed64, Fixed64)

Returns the arithmetic midpoint of two fixed-point values without intermediate overflow.

public static Fixed64 Midpoint(Fixed64 left, Fixed64 right)

Parameters

left Fixed64
right Fixed64

Returns

Fixed64

Remarks

A midpoint exactly between two raw Q32.32 values is rounded to the nearest even raw value.

Min(Fixed64, Fixed64)

Returns the smaller of two fixed-point values.

public static Fixed64 Min(Fixed64 a, Fixed64 b)

Parameters

a Fixed64
b Fixed64

Returns

Fixed64

MoveTowards(Fixed64, Fixed64, Fixed64)

Moves a value from 'from' to 'to' by a maximum step of 'maxAmount'. Ensures the value does not exceed 'to'.

public static Fixed64 MoveTowards(Fixed64 from, Fixed64 to, Fixed64 maxAmount)

Parameters

from Fixed64
to Fixed64
maxAmount Fixed64

Returns

Fixed64

Pow(Fixed64, Fixed64)

Raises the base number b to the power of exp. Uses logarithms to compute power efficiently for fixed-point values.

public static Fixed64 Pow(Fixed64 b, Fixed64 exp)

Parameters

b Fixed64
exp Fixed64

Returns

Fixed64

Exceptions

DivideByZeroException

The base was Fixed64.Zero, with a negative expFixed64.Onent

ArgumentOutOfRangeException

The base was negative, with a non-Fixed64.Zero expFixed64.Onent

Pow2(Fixed64)

Raises 2 to the power of x. Provides high accuracy for small values of x.

public static Fixed64 Pow2(Fixed64 x)

Parameters

x Fixed64

Returns

Fixed64

RadToDeg(Fixed64)

Converts a value in radians to degrees.

public static Fixed64 RadToDeg(Fixed64 rad)

Parameters

rad Fixed64

Returns

Fixed64

Round(Fixed64, MidpointRounding)

Rounds a fixed-point number to the nearest integral value, based on the specified rounding mode.

public static Fixed64 Round(Fixed64 value, MidpointRounding mode = MidpointRounding.ToEven)

Parameters

value Fixed64
mode MidpointRounding

Returns

Fixed64

RoundToPrecision(Fixed64, int, MidpointRounding)

Rounds a fixed-point number to a specific number of decimal places.

public static Fixed64 RoundToPrecision(Fixed64 value, int decimalPlaces, MidpointRounding mode = MidpointRounding.ToEven)

Parameters

value Fixed64
decimalPlaces int
mode MidpointRounding

Returns

Fixed64

Sin(Fixed64)

Computes the sine of a given angle in radians using complementary reduced-range polynomial approximations.

public static Fixed64 Sin(Fixed64 x)

Parameters

x Fixed64

The angle in radians.

Returns

Fixed64

The sine of the given angle, in fixed-point format.

Remarks

The input is normalized to [-π, π], reflected into [0, π/2], and evaluated as sine on [0, π/4] or cosine on [0, π/4]. Exact quadrant anchors remain exact without introducing a discontinuity beside them.

SinToCos(Fixed64)

Calculates the cosine value corresponding to a given sine value, assuming the angle is in the first or second quadrant.

public static Fixed64 SinToCos(Fixed64 sin)

Parameters

sin Fixed64

The sine of the angle. Must be in the range [-1, 1].

Returns

Fixed64

The cosine of the angle, computed as the positive square root of (1 - sin²).

Remarks

This method returns the principal (non-negative) value of the cosine. If the input is outside the valid range for sine values, the result may not be meaningful.

SmoothStep(Fixed64, Fixed64, Fixed64)

Performs a smooth step interpolation using a cubic Hermite curve between two values.

public static Fixed64 SmoothStep(Fixed64 a, Fixed64 b, Fixed64 t)

Parameters

a Fixed64

The starting value.

b Fixed64

The ending value.

t Fixed64

A value between 0 and 1 that represents the interpolation factor.

Returns

Fixed64

The interpolated value between a and b.

Remarks

The interpolation follows a cubic Hermite curve where the function starts at a, accelerates, and then decelerates towards b, ensuring smooth transitions.

Sqrt(Fixed64)

Returns the square root of a specified fixed-point number.

public static Fixed64 Sqrt(Fixed64 x)

Parameters

x Fixed64

Returns

Fixed64

Squared(Fixed64)

Squares the Fixed64 value.

public static Fixed64 Squared(Fixed64 value)

Parameters

value Fixed64

The Fixed64 value to square.

Returns

Fixed64

The squared value.

SumBarycentricProducts(Fixed64, Fixed64, Fixed64, Fixed64, Fixed64, Fixed64)

Returns the cross scalar product sum for two sets of three barycentric vertices.

public static Fixed64 SumBarycentricProducts(Fixed64 firstA, Fixed64 firstB, Fixed64 firstC, Fixed64 secondA, Fixed64 secondB, Fixed64 secondC)

Parameters

firstA Fixed64
firstB Fixed64
firstC Fixed64
secondA Fixed64
secondB Fixed64
secondC Fixed64

Returns

Fixed64

SumSquaredBarycentricProducts(Fixed64, Fixed64, Fixed64)

Returns the second-order scalar product sum for three barycentric vertices.

public static Fixed64 SumSquaredBarycentricProducts(Fixed64 a, Fixed64 b, Fixed64 c)

Parameters

a Fixed64
b Fixed64
c Fixed64

Returns

Fixed64

Remarks

Computes a * a + b * b + c * c + a * b + a * c + b * c.

Tan(Fixed64)

Returns the tangent of x.

public static Fixed64 Tan(Fixed64 x)

Parameters

x Fixed64

Returns

Fixed64

Remarks

This function is not well-tested. It may be wildly inaccurate.

TryGetCircleCrossSectionRadius(Fixed64, Fixed64, out Fixed64)

Attempts to get the radius of a circular sphere cross-section at the specified signed distance from the sphere center.

public static bool TryGetCircleCrossSectionRadius(Fixed64 radius, Fixed64 offset, out Fixed64 crossSectionRadius)

Parameters

radius Fixed64

The non-negative sphere radius.

offset Fixed64

The signed distance from the sphere center to the cross-section plane.

crossSectionRadius Fixed64

The nearest-even cross-section radius, or zero when the plane misses the sphere.

Returns

bool

true when the plane intersects or is tangent to the sphere; otherwise, false.

Remarks

The difference of squares and square root remain exact until the final deterministic Fixed64 conversion.

Exceptions

ArgumentOutOfRangeException

radius is negative.

TryGetSphereSlabCrossSectionRadius(Fixed64, Fixed64, Fixed64, Fixed64, out Fixed64)

Attempts to get the largest circular sphere cross-section that lies within a centered finite slab.

public static bool TryGetSphereSlabCrossSectionRadius(Fixed64 sphereCenter, Fixed64 sphereRadius, Fixed64 slabCenter, Fixed64 slabHalfThickness, out Fixed64 crossSectionRadius)

Parameters

sphereCenter Fixed64

The sphere-center coordinate on the slab axis.

sphereRadius Fixed64

The non-negative sphere radius.

slabCenter Fixed64

The slab-center coordinate on the same axis.

slabHalfThickness Fixed64

The non-negative slab half-thickness.

crossSectionRadius Fixed64

The nearest-even radius at the slab plane closest to the sphere center, or zero when the slab and sphere do not intersect.

Returns

bool

true when the slab intersects or is tangent to the sphere; otherwise, false.

Remarks

Center separation, slab projection, the difference of squares, and the square root remain exact until the final deterministic Fixed64 conversion.

Exceptions

ArgumentOutOfRangeException

sphereRadius or slabHalfThickness is negative.