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
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
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
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
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
MIN_VALUE_L
Represents the smallest possible value for a 64-bit fixed-point number.
public const long MIN_VALUE_L = -9223372036854775808
Field Value
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
SCALE_FACTOR_D
Represents the precomputed scale factor used for double-precision calculations.
public const double SCALE_FACTOR_D = 2.3283064365386963E-10
Field Value
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
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
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
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
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
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
valueFixed64
Returns
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
xFixed64The 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
xFixed64The 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
zFixed64
Returns
Atan2(Fixed64, Fixed64)
Computes the angle whose tangent is the quotient of two specified numbers.
public static Fixed64 Atan2(Fixed64 y, Fixed64 x)
Parameters
yFixed64The y-coordinate of the point to which the angle is measured.
xFixed64The 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
Returns
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
coordAFixed64The coordinate of the first vertex.
coordBFixed64The coordinate of the second vertex.
coordCFixed64The coordinate of the third vertex.
weightBFixed64The barycentric weight for the second vertex.
weightCFixed64The 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
p0Fixed64The first control point.
p1Fixed64The second control point.
p2Fixed64The third control point.
p3Fixed64The fourth control point.
tFixed64Interpolation 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
valueFixed64
Returns
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
Returns
Clamp01(Fixed64)
Clamps value between 0 and 1 and returns value.
public static Fixed64 Clamp01(Fixed64 value)
Parameters
valueFixed64
Returns
ClampOne(Fixed64)
Clamps the value between -1 and 1 inclusive.
public static Fixed64 ClampOne(Fixed64 f1)
Parameters
f1Fixed64The 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
valueTThe value to clamp.
minTThe minimum allowed value.
maxTThe maximum allowed value.
Returns
- T
The clamped value.
Type Parameters
TThe 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
Returns
Cos(Fixed64)
Computes the cosine of a given angle in radians using a sine-based identity transformation.
public static Fixed64 Cos(Fixed64 x)
Parameters
xFixed64The 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 identitycos(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
p0Fixed64The first point.
p1Fixed64The second point.
m0Fixed64The tangent at
p0.m1Fixed64The tangent at
p1.tFixed64A value between 0 and 1 that represents the interpolation factor.
Returns
- Fixed64
The interpolated value between
p0andp1.
DegToRad(Fixed64)
Converts a value in degrees to radians.
public static Fixed64 DegToRad(Fixed64 deg)
Parameters
degFixed64
Returns
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
Returns
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
Returns
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
Returns
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
Returns
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
Returns
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
valueFixed64
Returns
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
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
value1Fixed64The first value.
tangent1Fixed64The tangent at the first value.
value2Fixed64The second value.
tangent2Fixed64The tangent at the second value.
amountFixed64The 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
fromFixed64The starting value.
toFixed64The ending value.
tFixed64A value between 0 and 1 that represents the interpolation factor.
Returns
- Fixed64
The interpolated value between
fromandto.
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
xFixed64
Returns
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
xFixed64
Returns
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
Returns
Midpoint(Fixed64, Fixed64)
Returns the arithmetic midpoint of two fixed-point values without intermediate overflow.
public static Fixed64 Midpoint(Fixed64 left, Fixed64 right)
Parameters
Returns
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
Returns
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
Returns
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
Returns
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
xFixed64
Returns
RadToDeg(Fixed64)
Converts a value in radians to degrees.
public static Fixed64 RadToDeg(Fixed64 rad)
Parameters
radFixed64
Returns
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
valueFixed64modeMidpointRounding
Returns
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
valueFixed64decimalPlacesintmodeMidpointRounding
Returns
Sin(Fixed64)
Computes the sine of a given angle in radians using complementary reduced-range polynomial approximations.
public static Fixed64 Sin(Fixed64 x)
Parameters
xFixed64The 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
sinFixed64The 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
aFixed64The starting value.
bFixed64The ending value.
tFixed64A value between 0 and 1 that represents the interpolation factor.
Returns
- Fixed64
The interpolated value between
aandb.
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
xFixed64
Returns
Squared(Fixed64)
Squares the Fixed64 value.
public static Fixed64 Squared(Fixed64 value)
Parameters
valueFixed64The 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
Returns
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
Returns
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
xFixed64
Returns
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
radiusFixed64The non-negative sphere radius.
offsetFixed64The signed distance from the sphere center to the cross-section plane.
crossSectionRadiusFixed64The nearest-even cross-section radius, or zero when the plane misses the sphere.
Returns
Remarks
The difference of squares and square root remain exact until the final deterministic Fixed64 conversion.
Exceptions
- ArgumentOutOfRangeException
radiusis 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
sphereCenterFixed64The sphere-center coordinate on the slab axis.
sphereRadiusFixed64The non-negative sphere radius.
slabCenterFixed64The slab-center coordinate on the same axis.
slabHalfThicknessFixed64The non-negative slab half-thickness.
crossSectionRadiusFixed64The nearest-even radius at the slab plane closest to the sphere center, or zero when the slab and sphere do not intersect.
Returns
Remarks
Center separation, slab projection, the difference of squares, and the square root remain exact until the final deterministic Fixed64 conversion.
Exceptions
- ArgumentOutOfRangeException
sphereRadiusorslabHalfThicknessis negative.