MathAssertions 0.6.0
Prefix Reserveddotnet add package MathAssertions --version 0.6.0
NuGet\Install-Package MathAssertions -Version 0.6.0
<PackageReference Include="MathAssertions" Version="0.6.0" />
<PackageVersion Include="MathAssertions" Version="0.6.0" />
<PackageReference Include="MathAssertions" />
paket add MathAssertions --version 0.6.0
#r "nuget: MathAssertions, 0.6.0"
#:package MathAssertions@0.6.0
#addin nuget:?package=MathAssertions&version=0.6.0
#tool nuget:?package=MathAssertions&version=0.6.0
MathAssertions
Scope: Test projects only. Not intended for production code.
Part of the DotNetAssertions family. This is the framework-agnostic core; the TUnit assertions live in the matching
.TUnitpackage.
Framework-agnostic core of the MathAssertions package family. Math assertion helpers for .NET tests, spanning tolerance comparisons, sequences, statistics, linear algebra, number theory, and 3D geometry. Test-framework-specific entry points ship in adapter packages (currently MathAssertions.TUnit for TUnit).
Most users want
MathAssertions.TUnit, not this package directly. This package ships the framework-agnostic helper classes (MathTolerance,Sequences,Statistics,LinearAlgebra,NumberTheory, plus theGeometry3Dnamespace andPoseRenderer); the adapter package adds the fluentAssert.That(value).Method(...)entry points your test framework expects.
What's in this package
Pure mathematical-assertion helpers. The tolerance comparisons handle NaN and infinity explicitly, the generic ReadOnlyTensorSpan<T> overload included (an integer difference beyond the range of the element type compares unequal instead of wrapping). The checks that test a bound fail on NaN instead of passing. Five static classes in the MathAssertions namespace, PoseRenderer in MathAssertions.Render, and the MathAssertions.Geometry3D namespace cover ~85 methods:
MathTolerance: scalarIsApproximatelyEqualfordouble/floatplusAngleDifferenceDegreesandIsAngleApproximatelyEqual(angles in degrees on the circle that wraps every 360 degrees) and theSystem.Numericscompounds (Vector2/Vector3/Vector4,QuaternionwithIsRotationallyEquivalentand (v0.2.0+)HasAxisAngleApproximately,Matrix4x4,PlanewithIsGeometricallyEquivalent,Complex), span / tensor overloads (ReadOnlySpan<double>/<float>, genericReadOnlyTensorSpan<T>), ULP-distance equality (IsCloseInUlps), combined relative+absolute tolerance, finiteness/probability/percentage predicates,HasRoundtripIdentityfor invertible-transformation checks, and (v0.4.0+) the pose primitivesRotationAngleDegrees,PositionDistance, andIsPoseApproximatelyEqual.- (v0.2.0+) Adapter packages such as
MathAssertions.TUnituse an internal per-component / per-cell / first-failing-element failure-message renderer so every compoundIsApproximatelyEqualTofailure shows the diverging axis and its delta. The renderer is reachable across the assembly boundary via[InternalsVisibleTo]; consumers do not interact with it directly. Sequences: monotonicity (strict + non-strict), boundedness, arithmetic and geometric progressions,ConvergesTo, single-stepIsCauchyConvergent, generic length predicates overReadOnlySpan<T>.Statistics: Welford'sMeanAndVariance,HasMean/Variance/StdDev/Sum/Median/PercentileApproximately,IsWithinSigmasOfMean,AreAllWithinSigmasOfMean. Median and percentile use overflow-safe forms. The XML docs and the main README state the NaN behavior of every method and the unit of each tolerance.LinearAlgebra:Matrix4x4invariants (IsSymmetric,IsOrthogonal,IsRotation,IsIdentity,HasDeterminantApproximately,HasTraceApproximately,IsInvertible) plusVector3pair properties (AreOrthogonal,AreParallel(scale-invariant),AngleBetween,AreLinearlyIndependent).NumberTheory: exact integer predicates overlong:IsDivisibleBy,IsPrime,AreCoprime,GreatestCommonDivisor,LeastCommonMultiple,IsPowerOf,IsPerfectSquare,IsCongruent. Primality and perfect-square checks are overflow-safe, and GCD/LCM handlelong.MinValue;IsDivisibleByistruefor a divisor of1or-1, includinglong.MinValue.PoseRenderer(MathAssertions.Render, public since v0.3.0): renders a position / orientation pose as deterministic, snapshot-friendly text.Geometry3D: eight primitiverecord structtypes (Sphere,AxisAlignedBox,OrientedBox,Ray3D,LineSegment3D,Triangle3D,Capsule,Cylinder) and five static classes:Properties(degeneracy, collinearity, coplanarity),Containment(point/box/sphere/OBB/convex hull),Distance(point-to-plane/segment/triangle),Intersection(sphere-sphere, AABB-AABB, ray-plane/sphere/triangle/AABB with citations to Real-Time Rendering §§22.6, 22.7, 22.8),Pointcloud(boundedness, centroid, on-plane / on-sphere). Algorithm citations preserved per Real-Time Collision Detection and Real-Time Rendering.
All tolerance- and sigma-taking methods validate the bound up front; invalid input throws ArgumentOutOfRangeException even on early-return paths.
Test-framework adapters
| Package | Test framework | Status |
|---|---|---|
MathAssertions.TUnit |
TUnit | Available now |
Adapters for other test frameworks (NUnit, xUnit, MSTest) are not planned; the family targets TUnit.
When to install this package directly
Only when authoring a non-TUnit adapter for the assertion family, or when calling MathTolerance from a [GenerateAssertion] extension on a private type. For any TUnit testing use case, install MathAssertions.TUnit.
Installation
dotnet add package MathAssertions.TUnit
MathAssertions comes transitively. You don't need to install it directly unless you're building your own adapter package.
Stability
The public surface above is semver-bound. This is a 0.x release: additive changes ship in any release, and breaking changes bump the minor version (0.X.0) and are called out in the CHANGELOG. The exact text of the failure messages, rendered by an internal helper in this package, is not stable and may gain extra detail or change formatting in any release.
Repository
github.com/JohnVerheij/MathAssertions.TUnit for the full README, design notes, and roadmap.
License
MIT. Copyright (c) 2026 John Verheij.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net10.0 is compatible. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. net11.0 is compatible. |
-
net10.0
- System.Numerics.Tensors (>= 10.0.15)
-
net11.0
- System.Numerics.Tensors (>= 11.0.0)
NuGet packages (1)
Showing the top 1 NuGet packages that depend on MathAssertions:
| Package | Downloads |
|---|---|
|
MathAssertions.TUnit
TUnit-native math assertions for .NET tests. Fluent .Method(...) entry points (generated via TUnit's [GenerateAssertion]) covering tolerance comparisons (scalar, vector, quaternion, matrix, plane, complex, double[]/float[]), sequences, statistics, Vector3 linear algebra, long-integer number theory, and the Geometry3D primitive surface (containment, distance, intersection, pointcloud aggregates). Extensible: consumers add tolerance assertions for their own domain types via [GenerateAssertion] extensions calling MathTolerance helpers. AOT-compatible, trimmable, no reflection. |
GitHub repositories
This package is not used by any popular GitHub repositories.
View the rendered release notes: https://github.com/JohnVerheij/MathAssertions.TUnit/releases/tag/v0.6.0
### Added
- **`MathTolerance.AngleDifferenceDegrees(double, double)` and `MathTolerance.AngleDifferenceDegrees(float, float)`:** the shorter arc between two angles in degrees, in `[0, 180]`: `359` and `1` are `2` apart and `180` and `-180` are `0` apart. Each angle is reduced to `[-180, 180]` first (the IEEE remainder, exact, so huge angles keep their precision and nothing overflows), and two angles on both sides of `180` are compared after one moves a full turn, so a difference of one ulp is not rounded to a full turn; a NaN or infinite angle gives NaN. The `float` overload computes in `double` and rounds once.
- **`MathTolerance.IsAngleApproximatelyEqual(double, double, double)` and `MathTolerance.IsAngleApproximatelyEqual(float, float, float)`:** `true` when the wrapped difference is at most the tolerance in degrees. A NaN or infinite angle never matches, not even NaN against NaN.
- **`ScalarAssertions.IsAngleApproximatelyEqualTo` for `double` and for `float`:** the fluent form, `await Assert.That(yawDegrees).IsAngleApproximatelyEqualTo(-180f, toleranceDegrees: 0.05f)`. The failure message shows the actual angle, the expected angle and the wrapped difference. The generator adds the public assertion classes `Double_IsAngleApproximatelyEqualTo_Double_Double_Assertion` and `Float_IsAngleApproximatelyEqualTo_Float_Float_Assertion` to `MathAssertions.TUnit`.
- **.NET 11:** both packages now target `net10.0` and `net11.0` (`net10.0` only before). `System.Numerics.Tensors` is 10.0.15 for `net10.0` and 11.0.0 for `net11.0`. The family policy is now to target every .NET version in Microsoft support (`CONVENTIONS.md`, "TFM policy").
### Changed
- **`TUnit.Assertions`** and **`TUnit.Core`** minimum versions raised from 1.81.10 to 1.85.0: 1.83.0 is the first TUnit with a `net11.0` asset, and 1.85.0 keeps TUnit's OpenTelemetry and ASP.NET Core packages on OpenTelemetry 1.20.x for `net10.0`, so a project with one version for all its TUnit packages gets no .NET 11 packages there.
- **`MathTolerance.IsPoseApproximatelyEqual` and `IsPoseApproximatelyEqualTo`:** a position whose distance is NaN (a NaN coordinate, or infinite coordinates that cancel) now fails; it used to pass because the distance was NaN and the comparison `NaN > tolerance` is `false`.
- **`Containment.ConvexHullContains` and `ConvexHullContainsPoint`:** a NaN point or a NaN hull vertex now fails (it passed), and a hull in which every face triangle is degenerate (zero area) now contains no point (it contained every point). The faces are computed in `double`, so a tiny but valid hull (sides near `1e-12`) is not taken for a degenerate one.
- **`Pointcloud.IsApproximatelyOnPlane`, `IsApproximatelyOnSphere` and the adapter assertions of the same names:** a cloud with a NaN point now fails (it passed).
- **`Sequences.IsMonotonicallyIncreasing`, `IsMonotonicallyDecreasing`, `IsStrictlyMonotonicallyIncreasing`, `IsStrictlyMonotonicallyDecreasing`, `IsSorted` and the adapter assertions of the same names:** a span containing NaN now returns `false`, a one-element span `[NaN]` included (NaN passed whenever its neighbors were ordered, and a single NaN was vacuously monotonic).
- **`Properties.IsCollinear` and `Properties.AreCoplanar` (and the adapter assertions):** a point with a NaN or infinite coordinate now returns `false` (an all-NaN set was collinear and coplanar, and one NaN point was ignored).
- **`MathTolerance.IsRotationallyEquivalent`, `HasAxisAngleApproximately`, `IsPoseApproximatelyEqual` and the adapter assertions:** a quaternion with a NaN or infinite component now never matches, not even itself; it used to take the componentwise fallback of the zero quaternion, where NaN equals NaN (`new Quaternion(float.NaN, 0, 0, 1)` against itself passed). The componentwise fallback at `1e-6` stays for the exactly-zero quaternion.
- **`Intersection.Intersects(Ray3D, AxisAlignedBox)`:** a ray whose origin has a NaN coordinate on an axis the ray runs parallel to now misses the box (it hit).
- **`LinearAlgebra.IsRotation` and the adapter assertion `IsRotation`:** now also requires the last column `0, 0, 0, 1` within the tolerance (`M14`, `M24`, `M34` near `0`, `M44` near `1`). A rotation that mixes W with X, Y or Z (for example `M14 = sin 0.5`) used to pass and now fails; `diag(1, 1, -1, -1)`, orthogonal with determinant `+1` and `M44 = -1`, now fails too. `IsOrthogonal` stays a pure 4x4 check and still accepts both. Rotations, `CreateScale(-1, -1, 1)` and the documented tolerance rows are unchanged.
- **`MathTolerance.IsRotationallyEquivalent`, `HasAxisAngleApproximately` and the adapter assertions:** now compute in `double` precision. A non-unit quaternion compared with itself or a scaled copy passes a tolerance such as `1e-12` (it could fail by the `float` rounding of its normalization), and the expected axis-angle rotation is built in `double`. A quaternion that cannot be normalized (the zero quaternion) is compared componentwise at a fixed tolerance of `1e-6`, the rule `IsPoseApproximatelyEqual` already had: the zero quaternion now matches itself and no real rotation (it matched nothing, itself included).
- **`Statistics` (all nine methods) and the statistics assertions:** the XML docs, both READMEs and a new README table now state what each method does with a NaN in the sample and the unit of each tolerance (the unit of the values; the squared unit for the variance; a multiple of the standard deviation for `sigmas`; percentiles on the scale 0 to 100). The behavior is unchanged.
### Fixed
- **`Properties.AreCoplanar`:** now picks the plane from a triple whose third point lies farther than the tolerance (a length) from the line through the first two, as `IsCollinear` does. It compared the length of a cross product (an area) with the tolerance, so a small point set passed whatever its shape: `(0, 0, 0)`, `(0.01, 0, 0)`, `(0, 0.01, 0)` and `(0, 0, 0.01)` were coplanar under a tolerance of `0.001`. Leading points within the tolerance of the first (coincident or near-coincident, as in `IsCollinear`) are skipped, as their direction is noise: with the second point 1e-4 from the first and a tolerance of 1e-3, the coplanar set `(0, 0, 0)`, `(0, 0, 1e-4)`, `(1, 0, 0)`, `(0, 1, 0)`, `(1, 1, 0)` is no longer rejected.
- **`MathTolerance.IsApproximatelyEqual<T>` (`ReadOnlyTensorSpan<T>`):** no longer overflows in the difference and now applies the scalar infinity rules under every tolerance. An unsigned `0` against `1` wrapped to a huge difference and compared unequal under a tolerance of `1`; `int.MinValue` against `0` threw `OverflowException`; `int.MaxValue` against `int.MinValue` wrapped to `-1` and compared equal under any tolerance of `1` or more. Under a tolerance of positive infinity, opposite-sign infinities and an infinity against a finite value returned `true`; they now return `false`, like the scalar overloads. A difference beyond the range of an integer type counts as larger than any tolerance. For `float` and `Half` elements the difference is formed in `double`, as in the scalar overloads: `16777216f` against `-1f` (`16777217` apart) was equal under a tolerance of `16777216f`.
- **`MathTolerance.HasAxisAngleApproximately`:** the expected axis is normalized in `double`. An axis such as `(1e30, 0, 0)` or `(1e-30, 0, 0)` keeps its direction (the first normalized to `(0, 0, 0)` and silently expected the identity, the second threw), so the `ArgumentException` now happens only for an axis of exactly zero length or with a NaN or infinite component.
- **`LinearAlgebra.AreParallel` and the adapter assertion `IsParallelTo`:** the lengths and the cross product are now computed in `double`, so the result no longer depends on the `float` range. Before, `(1e15, 0, 0)` against `(1e15, 1e12, 0)` (a sine of `1e-3`) failed under a tolerance of `1e-2`, and `(1e20, 0, 0)` against the orthogonal `(0, 1e-3, 0)` passed as parallel under `1e-4`, because the squares overflowed. The limit of about `1.8e19` is gone.
- **`NumberTheory.IsDivisibleBy` and the adapter assertion:** now returns `true` for a divisor of `1` or `-1`, including `long.MinValue` with `-1` (it threw `OverflowException`).
- **`Statistics.HasMedianApproximately`:** the even-length midpoint no longer loses a denormal: the median of `[double.Epsilon, double.Epsilon]` is `double.Epsilon` (it was `0`, the result of halving each operand). The midpoint is correctly rounded: `[double.Epsilon, 2 * double.Epsilon]` gives `2 * double.Epsilon`, `[1, 1e16]` gives `5e15`. Large values still do not overflow.
- **`Statistics.MeanAndVariance`, `HasMeanApproximately`, `HasStdDevApproximately`, `IsWithinSigmasOfMean` and `AreAllWithinSigmasOfMean`:** the mean of a finite sample is now exact: the values are summed exactly and the sum divided by the count is rounded once to the nearest `double`, in any order and at any magnitude. The mean of `[double.MaxValue, -double.MaxValue]` is `0` (it was infinite, as the difference of the two overflowed), `[2^500, 2^200, 1, -2^200, -2^500]` has the mean `0.2`, and `[0.5, -0.5, 2 * double.Epsilon]` has the mean `double.Epsilon`. The variance comes from the sample centered on its smallest value and scaled by a power of two of its spread, so its squares neither overflow nor underflow, and values only a few units in the last place apart keep their variance (`[1 + 2^-52, 1]` has the variance `2^-105`). The standard deviation of `[1e200, 3e200]` is `1.41e200` and that of `[1e-200, 3e-200]` is `1.41e-200` (the variance overflowed or underflowed, so the checks saw infinity or zero). The sigma checks keep their envelope as a mantissa and a power of two, so it neither overflows nor rounds in the denormal range: an outlier no longer passes an infinite envelope (`[0, 0, 0, 0, 0, 0, 0, 0, 0, 1e200]` fails at one sigma), `[-double.MaxValue, double.MaxValue]` fails at half a sigma (each value is about 0.707 standard deviations from the mean), and a tiny sigma count or a sample of denormals is judged as precisely as any other. The variance itself is infinite only when it does not fit in a `double`. The mean can differ from 0.5.1 in the last digit (it is now the correctly rounded mean; the running mean was often one unit in the last place off), and so can the variance.
- **`Statistics.HasSumApproximately`:** the sum of a finite sample is now exact, rounded once to the nearest `double`, in any order: `[double.MaxValue, double.MaxValue, -double.MaxValue]` sums to `double.MaxValue` (a running sum overflowed and reported infinity), and `[1e300, 1e200, 1, -1e200, -1e300]` sums to `1` (it was `0`). The sum is infinite only when it does not fit.
- **`Statistics.HasPercentileApproximately`:** two equal neighbors now give exactly that value; the interpolation `a * (1 - f) + b * f` of `3.3` and `3.3` at 7 percent was `3.2999999999999994`, which failed a tolerance of zero.
- **`Sequences.IsArithmeticProgression` and `IsGeometricProgression`:** a sequence that contains a NaN or an infinity now returns `false`; a NaN difference or ratio equaled itself, so `[1, NaN, NaN]` and `[NaN, NaN, NaN]` were progressions.
- **`LinearAlgebra.AreLinearlyIndependent`:** a vector with a NaN or infinite component now makes the result `false` for every count of vectors (a pair read "not parallel" off the NaN and was independent). The length of a single vector and the triple product of three are computed in `double`, so `(1e-30, 0, 0)` is independent under a tolerance of `1e-35` and three vectors of length `1e-20` have a volume of `1e-60` (both underflowed to zero).
- **`LinearAlgebra.AreOrthogonal` and `AngleBetween`:** the dot and cross products are computed in `double`. `(1e20, 1e20, 0)` and `(1e20, -1e20, 0)` are orthogonal (the `float` products overflowed and the sum was NaN), and `(1e-30, 0, 0)` and `(0, 1e-30, 0)` are `pi / 2` apart (the products underflowed and the pair read as a zero vector, angle `0`).
- **`Properties.IsCollinear`:** the differences, lengths and cross products are computed in `double`, as in `AreCoplanar`. Finite points whose `float` difference overflowed (`(3e38, 0, 0)` against `(-3e38, 0, 0)`) gave a NaN distance that passed every further point, and an edge of `1e-30` underflowed to zero length under a tolerance of zero.
- **`Properties.IsDegenerate`:** the area is computed in `double`, so a tiny triangle (sides of `1e-25`) is not degenerate under a tolerance of zero (its `float` area underflowed to zero).
- **`Containment.Contains(Sphere, Vector3)`, `Contains(AxisAlignedBox, Sphere)`, `Intersection.Intersects(Sphere, Sphere)` and `Intersects(Ray3D, Sphere)`:** computed in `double`. Squares of `float` distances overflowed (a sphere of radius `1e20` contained a point at `1e30`) or underflowed (a sphere of radius `1e-25` contained a point at `2e-25`), a box contained a sphere that stuck out by one `float` ulp, and the ray test lost every digit for a distant sphere (it subtracted two squares of `1e60`; it now measures the perpendicular distance).
- **`Intersection.Intersects(Ray3D, Sphere)`:** no longer needs an exactly unit direction. The projection is divided by the squared direction length, so a direction normalized in `float` (a rounding away from unit length) hits a sphere centered on the ray `1e9` away, and a direction of any length gives the answer of the unit one; a zero direction hits only when the origin is inside the sphere.
- **`Distance.DistanceFrom` (plane, segment, triangle), `Pointcloud.IsApproximatelyOnPlane`, `IsApproximatelyOnSphere` and `HasCentroidAt`:** computed in `double`. A segment from `(-3e38, 0, 0)` to `(3e38, 0, 0)` gave NaN, a segment of length `1e-30` read as a point, a triangle of side `1e-25` measured the distance to its first vertex (and underflowed to zero), and the centroid of two points at `3e38` overflowed to infinity in the `float` sum.
- **`MathTolerance.IsApproximatelyEqual(float, float, float)` (and the `float` span overload):** the difference is formed in `double`. The `float` subtraction rounds, so `16777216f` and `-1f` (`16777217` apart) were equal under a tolerance of `16777216f`.
- **`MathTolerance.IsRelativelyAndAbsolutelyClose`:** two equal zeros are close under an infinite relative tolerance (the bound `infinity * 0` was NaN, and `Math.Max` passed it on).
- **`IsRotationallyEquivalentTo` failure message:** the dot and the normalized quaternions shown are the ones the check computed, in `double`. The `float` normalization of a quaternion near the identity rendered `|dot| = 1` for a check that failed on `0.99999999875`, and the zero quaternion rendered `NaN`; it now says that the quaternion cannot be normalized and is compared componentwise.