Skip to sessions and notes

These session notes are AI-generated and may contain mistakes. Verify important details against the original recording.

.NET 11 Numerics

Tanner Gooding

Session · 27:42 recording · 7 min read

At a glance

  • IEEE 754:2019 Decimal Floats (Decimal32, Decimal64, Decimal128)
  • Exact base-10 math (0.1 + 0.2 == 0.3) vs System.Decimal
  • Significant figures & Quantum tracking (HaveSameQuantum)
  • Google Brain Floating Point BFloat16 for AI dynamic range
  • Generic Complex decoupled from double

Executive Summary

In .NET 11, the System.Numerics ecosystem undergoes its most substantial evolution since the introduction of Generic Math in .NET 7. Led by Tanner Gooding, the .NET team delivered major architectural additions spanning three core pillars:

  1. New Numeric Representations: The long-awaited native implementation of IEEE 754:2019 Decimal Floating-Point types (Decimal32, Decimal64, Decimal128), and Google's Brain Floating Point (BFloat16), resolving decades of tension between binary floating-point rounding anomalies and non-standard decimal structures.
  2. Generic Complex Numbers & Math Consolidation: A fully generic Complex<T> replacing the legacy double-only implementation, allowing complex arithmetic over float, Decimal128, or any IFloatingPointIeee754<T>, backed by algorithm unification across all primitive types.
  3. Tensor Architecture & Performance: A massive algorithmic redesign of System.Numerics.Tensors.Tensor<T> and ReadOnlyTensorSpan<T>. Through layout-aware execution paths that walk memory in contiguous runs rather than individual scalar indices, dense additions achieve a 160x speedup (16.37 µs down to 0.114 µs), while gapped-row flattening speeds up by 9x (7.92 µs down to 0.875 µs), complemented by robust safety contracts for overlapping in-place copies and NaN-propagation semantics.

.NET 11 Numerics Title
.NET 11 Numerics Title


Architecture: .NET 11 Numerics Landscape

graph TD
    subgraph "IEEE 754 Floating-Point Types"
        F16[Half - 16-bit float]
        BF16[BFloat16 - 16-bit AI float]
        F32[Single / float - 32-bit]
        F64[Double - 64-bit]
        D32[Decimal32 - 7 digits]
        D64[Decimal64 - 16 digits]
        D128[Decimal128 - 34 digits]
    end

    subgraph "Generic Math & Composed Types"
        GM["Generic Math Interfaces<br/>INumberBase&lt;T&gt;, IFloatingPointIeee754&lt;T&gt;"]
        CMPX["Complex&lt;T&gt;<br/>Complex&lt;float&gt;, Complex&lt;Decimal128&gt;"]
        RND["System.Random<br/>Next&lt;TInteger&gt;(), Next&lt;TFloat&gt;()"]
    end

    subgraph "Multi-Dimensional Execution"
        TS["Tensor&lt;T&gt; / TensorSpan&lt;T&gt;<br/>Dense, Strided, Gapped Views"]
        VEC["Hardware Intrinsics & FMA<br/>AVX-512, NEON, Layout-Aware Runs"]
        PARSE["TryParsePartial&lt;T&gt;<br/>Zero-allocation Token Scanning"]
    end

    D32 & D64 & D128 & BF16 & F32 & F64 --> GM
    GM --> CMPX
    GM --> RND
    GM --> TS
    TS --> VEC

1. IEEE 754 Decimal Floating-Point Types (Decimal32, Decimal64, Decimal128)

The Problem with Binary Floats and System.Decimal

For over two decades, .NET developers had to choose between two imperfect representations:

  • Binary Floats (float, double): Fast, hardware-accelerated IEEE 754 numbers, but unable to represent exact base-10 fractions (e.g. 0.1 + 0.2 yields 0.30000000000000004).
  • System.Decimal: High-precision 128-bit scaled integer designed in the 1990s for Win32 COM currency. It lacks standard IEEE concepts: no representation of positive or negative infinity, no signed zero (-0.0), and no NaN (Not-a-Number) values, throwing DivideByZeroException instead of following scientific IEEE semantics.

The .NET 11 Solution

.NET 11 introduces native IEEE 754:2019 base-10 decimal floating-point representations:

Type Bit Width Significant Decimal Digits Exponent Range Intended Use Case
Decimal32 32 bits 7 digits Base-10 IEEE format Memory-constrained telematics, embedded IoT, telemetry
Decimal64 64 bits 16 digits Base-10 IEEE format Standard financial modeling, transactional databases
Decimal128 128 bits 34 digits Base-10 IEEE format High-precision scientific computing, aerospace, cryptographic math

Decimal floating point, three sizes
Decimal floating point, three sizes

Quantum and Significant Intent

Unlike binary floating-point where 1.0 and 1.00 are identical bitwise representations, IEEE 754 decimal floating-point captures cohorts and the quantum (exponent scale) to reflect significant figures:

  • 1.0 has a quantum of 0.1 (1 decimal place).
  • 1.00 has a quantum of 0.01 (2 decimal places).
  • Decimal64.HaveSameQuantum(a, b) returns false between 1.0 and 1.00, enabling exact financial and regulatory audit trailing.
  • Decimal64.Quantize(1.235, 0.01) rounds deterministically to 1.24 according to IEEE rounding rules.

Same value. Different intent. Quantum and Quantize
Same value. Different intent. Quantum and Quantize

Live Demo: Exact Decimal Arithmetic & IEEE Semantics

In Tanner's live demonstration, Decimal64.Parse("0.1") + Decimal64.Parse("0.2") evaluates exactly to 0.3, while division by zero produces Infinity without runtime crashes.

Decimal64 a = Decimal64.Parse("0.1", CultureInfo.InvariantCulture);
Decimal64 b = Decimal64.Parse("0.2", CultureInfo.InvariantCulture);

// Binary double: 0.30000000000000004
// Decimal64:     0.3
Console.WriteLine($"Decimal64 sum: {a + b}"); 

Decimal64 onePlace = Decimal64.Parse("1.0", CultureInfo.InvariantCulture);
Decimal64 twoPlaces = Decimal64.Parse("1.00", CultureInfo.InvariantCulture);

Console.WriteLine($"Same value: {onePlace == twoPlaces}");           // True
Console.WriteLine($"HaveSameQuantum: {Decimal64.HaveSameQuantum(onePlace, twoPlaces)}"); // False
Console.WriteLine($"Quantum of 1.0: {Decimal64.GetQuantum(onePlace)}");   // 0.1
Console.WriteLine($"Quantum of 1.00: {Decimal64.GetQuantum(twoPlaces)}"); // 0.01

// IEEE division by zero produces Infinity (no exception)
Decimal64 inf = Decimal64.One / Decimal64.Zero; // Infinity

Visual Studio DecimalDemo output
Visual Studio DecimalDemo output


2. BFloat16: AI-Native Brain Floating Point

For artificial intelligence workloads (LLMs, vision encoders, diffusion models), memory bandwidth is the primary bottleneck. .NET now natively supports Google's Brain Floating Point format (System.Numerics.BFloat16).

Bit Allocation: Half vs BFloat16 vs Single

Type Total Bits Sign Bits Exponent Bits Mantissa (Fraction) Bits Dynamic Range
Half (float16) 16 1 5 10 ~$10^{-5}$ to ~$6.5 \times 10^4$ (High precision near 1.0, narrow range)
BFloat16 16 1 8 7 ~$10^{-38}$ to ~$3.4 \times 10^{38}$ (Same dynamic range as float32)
Single (float32) 32 1 8 23 ~$10^{-38}$ to ~$3.4 \times 10^{38}$

16 bits. Different priorities: Half vs BFloat16
16 bits. Different priorities: Half vs BFloat16

  • Direct Truncation Advantage: Because BFloat16 shares the identical 8-bit exponent layout with IEEE Single (float32), converting a float to BFloat16 is a fast truncation of the lower 16 bits of the mantissa (with standard round-to-nearest-even tie handling), requiring no exponent shifting or complex normalization logic.
  • AI Model Footprint: Cuts transformer weight memory by 50% relative to Single while preventing underflow/overflow during gradient backpropagation and attention-matrix calculation.

3. Generic Complex Numbers (Complex<T>)

Historically, System.Numerics.Complex was locked to double. .NET 11 replaces this with Complex<T> constrained to IFloatingPointIeee754<T>:

// Operate over float, double, Half, or Decimal128
Complex<float> binaryComplex = new(3.0f, 4.0f);
Complex<Decimal128> decimalComplex = new(
    Decimal128.CreateChecked(3), 
    Decimal128.CreateChecked(4)
);

// Generic function operating over any numeric type T
private static T Square<T>(T value) where T : INumberBase<T> 
    => value * value;

// Reused directly across scalar and complex representations:
Decimal128 scalarSquare = Square(Decimal128.Parse("1.25", CultureInfo.InvariantCulture));
Complex<float> floatComplexSquare = Square(binaryComplex);
Complex<Decimal128> decComplexSquare = Square(decimalComplex);

Generic Complex Demo
Generic Complex Demo

This consolidation eliminated thousands of lines of duplicated algorithmic code within the .NET CoreCLR/CoreLib BCL, allowing single source algorithms to serve byte, int, nint, float, double, decimal, decimal128, and their complex counterparts.


4. Tensors: Layout-Aware Execution & 160x Acceleration

Tensors represent multidimensional abstractions over continuous or strided memory. While introduced in .NET 8 and expanded in .NET 10, .NET 11 re-architects tensor walking to be layout-aware.

Contiguous Runs vs Individual Indexing

Previously, operations over non-dense or sliced tensors evaluated indices element-by-element, incurring heavy stride multiplication and boundary checking overhead. The .NET 11 engine detects contiguous sub-runs within gapped layouts, executing bulk vectorized SIMD over row chunks before stepping across stride gaps.

A slice can still have contiguous runs
A slice can still have contiguous runs

Performance Benchmarks (.NET 11 Backport on Ryzen 9 7950X)

Benchmark Scenario Input Dimensions Release Baseline .NET 11 Layout-Aware Speedup
Dense float Add 64x16 float inputs 16.37 µs 0.114 µs 143.6x (160x peak)
Gapped-row FlattenTo 64x16 gapped slices 7.92 µs 0.875 µs 9.05x

Tensor Benchmark Results
Tensor Benchmark Results

Correctness & Strided In-Place Safety

Accelerating memory copy and arithmetic operations required hardening corner cases where destination and source buffers overlap:

  • Dense Overlapping Copies: Handled safely via directional memory copy (e.g. [1, 2, 3, 4, 5] overlapping copy yields [1, 1, 2, 3, 4]).
  • Strided Non-Dense Overlapping Mutations: Because strided overlapping writes can corrupt source rows mid-operation without an intermediate buffer, .NET 11 strictly enforces safety contracts:
    • Detects unsafe non-dense strided overlaps.
    • Throws ArgumentException with the guarantee that the target buffer remains completely unchanged.
  • Vectorized Reductions: Full parity with Span<T> for IndexOf, IndexOfMax, IndexOfMin, MinMagnitude, incorporating strict IEEE NaN propagation (first NaN index returned) and tie-breaking guarantees.
int[] storage = [1, 2, -99, 3, 4, -99];
// Create a 2x2 matrix slice with column stride 1 and row stride 3
ReadOnlyTensorSpan<int> gapped = new(storage, lengths: [2, 2], strides: [3, 1]);

Span<int> flattened = stackalloc int[4];
gapped.FlattenTo(flattened); // [1, 2, 3, 4]

TensorDemo live output
TensorDemo live output


5. Numeric Building Blocks: System.Random & TryParsePartial

Generic System.Random

Historically, System.Random was restricted to Next(), NextInt64(), and NextDouble(). In .NET 11:

  • Random.Shared.Next<TInteger>(TInteger lower, TInteger upper) generates random values for any integer type (byte, short, Int128, BigInteger).
  • Random.Shared.Next<TFloatingPoint>() generates floating-point values in [0.0, 1.0) for Half, BFloat16, Single, Double, and Decimal128.

TryParsePartial: Zero-Allocation Token Scanning

Parsing structured streams (JSON tokens, CSV rows, Prometheus metrics, unit quantities like "12.5ms") previously forced developers to search for delimiters first or allocate substrings.

  • TryParsePartial parses numeric characters until encountering the first delimiter/non-numeric character.
  • Returns both the parsed numeric value and the exact character count consumed (charsConsumed), allowing instant, zero-allocation advancement of the input buffer.
  • Supports standard hexadecimal floating-point literals (e.g., 0x1.8p+1 evaluates to 3.0).

Keep numbers close to the data
Keep numbers close to the data


Key Takeaways for Developers

  1. Adopt Decimal64 / Decimal128 for Scientific & Modern Financial Code: Migrate off System.Decimal when strict IEEE 754 compliance, infinities, signed zero, or cohorts/quantum tracking are required.
  2. Leverage BFloat16 for AI & ML Pipelines: Halve RAM and VRAM consumption in local inference pipelines without suffering the underflow issues common to Half.
  3. Write Generic Math Once: Implement algorithms using INumberBase<T> and IFloatingPointIeee754<T> to gain automatic compatibility across scalars and Complex<T>.
  4. Upgrade Tensors for Free Speed: Existing Tensor<T> and TensorSpan<T> applications automatically benefit from 10x–160x speedups due to contiguous-run layout detection in the .NET 11 runtime.