Sr. Content Developer at Microsoft, working remotely in PA, TechBash conference organizer, former Microsoft MVP, Husband, Dad and Geek.
165139 stories
·
33 followers

Microsoft Sovereign Cloud demo: Choice and control for every workload

1 Share
From: MicrosoftAzure
Duration: 4:15
Views: 66

Discover how Microsoft Sovereign Cloud helps you apply the right level of control to every workload. The Sovereign Control Panel gives you oversight of your sovereignty posture in one Azure portal view, showing how your data residency, confidentiality, and business continuity controls are applied so you can drill in and act where it matters.

When continuity is the priority, the panel shows which workloads are ready to move from Azure to Azure Local, a private cloud you own and operate. Critical workloads can then shift to fully disconnected operations, running on a local control plane without interruption. Foundry Local and GitHub Enterprise Local bring AI models and developer tools right alongside your most sensitive data.

From oversight to operational independence, see how Microsoft Sovereign Cloud gives you the choice and control to meet your unique requirements.

Learn more at Microsoft Sovereign Cloud: https://msft.it/6057xDvRJ

Read the blog: https://msft.it/6058xDvRK

#SovereignControlPanel #AzureLocal #DigitalSovereignty

Read the whole story
alvinashcraft
just a second ago
reply
Pennsylvania, USA
Share this story
Delete

Small IT Teams Big Impact: Azure SRE Agent

1 Share
From: MicrosoftAzure
Duration: 4:22
Views: 624

How can small IT teams keep up with day-to-day responsibilities, and still find time to be proactive? Azure SRE Agent (Site Reliability Engineer Agent) streamlines IT work processes, helps you investigate and prevent issues, and automates routine tasks like reporting. Find out how Azure helps small and medium-sized businesses become more impactful through AI-enhanced tools like Azure SRE Agent.

Try Azure SRE Agent: https://msft.it/6050xDX5o

#SiteReliabilityEngineer #SRE #AzureSREAgent

Read the whole story
alvinashcraft
20 seconds ago
reply
Pennsylvania, USA
Share this story
Delete

Node.js 27.0.0-alpha.0.1.1 (Alpha)

1 Share
Read the whole story
alvinashcraft
34 seconds ago
reply
Pennsylvania, USA
Share this story
Delete

The pioneering coding tricks that built Doom and Quake

1 Share
Ryan chats with John Romero, creator of the WAD file and the video game Doom, about the self-modifying code and blitting techniques that made Wolfenstein run so fast on early PCs, the mod-friendly architecture that turned Doom into a cultural phenomenon, and why the raw creative problem-solving of Quake proves that human ideas will always beat AI coding agents.
Read the whole story
alvinashcraft
56 seconds ago
reply
Pennsylvania, USA
Share this story
Delete

Event Sourcing: the Timeline projector

1 Share

This is the last post in my series on Event Sourcing. In this post, we’ll take a deep dive into the Timeline projector that we use to project bi-temporal events into a timeline.

Quick reminder from earlier posts

There are two ways to create a timeline from events.

The version using create, update, and delete events, creates a timeline like show in this image:

The version using set and remove events creates a slightly different timelines:

I’ll guide you now through the whole TimelineProjector.fs file. All the below code samples are consecutive pieces from that file.

Types used for configuration of the projector

As seen in earlier examples, the CreateProjectionAction type is used to define how each event has to be interpreted for create-update-delete-timelines:

  • Creates: marks a creation event – the projection is “alive” from Effective onwards. E.g. an employee is created to exist from 13.11.2026 onwards. Since creation events hold all data needed to create the projection, the projection is passed as the second tuple value.
  • Updates: marks an event that updates an existing projection. The second tuple value is the function used to update the old projection to the new one. Again, Effective is the timestamp from which the updated value is available.
  • Deletes: deletes the projection at the given Effective.
  • ModifyPerpetually: the projection is updated over the whole timeline.
  • Skip: the event is skipped in this projection. This is useful when several different projections exist on the same event stream.

The SetProjectionAction is the equivalent for set-remove-based timelines:

  • Sets: sets a projection from Effective onwards.
  • Changes: updates a projection with the given Effective timestamp.
  • Removes: removes the projection from the timeline at Effective.
  • Skip: skips the event in this projection.

To complete the definition, we need some more configuration:

The OverrideBehavior defines how set-remove-based timelines deal with set events that have a later application, but an earlier effective than already existing set events. (see Event Sourcing: set-and-remove-based bi-temporal events)

ProjectionActionConfiguration defines which variant of the timeline we want to use.

Finally, the ProjectionConfiguration holds the above value plus a function that allows the projector to get the application timestamp of an event.

The Timeline Projector Module

The Timeline Projector module contains the functions to project a list of events given a projection configuration.:

Set-remove-based Timeline

shouldApplyEvent defines whether an event is ignored when the value it would set is overriden by an event with a smaller or equal effective timestamp, but a later application timestamp.

The folder function is the main part of the projection. We fold/loop over the events and build up the phases of the timeline. If the event should be applied, we determine how we need to interpret the event given the configuration (sets, changes, removes, or skipped). Then we build a new phase with the (updated) value. We add the phase to the current list of phases that is returned (= the phases in the next iteration of the loop). We build the phases in reverse order because adding at the front is faster.

Before we can call the folder function, we need to order the events correctly by their effective timestamp, application timestamp, and their kind. Ordering by kind is important so that, for example, when we have a Sets event and a Changes event with the same effective and application timestamps, the Sets event comes first.

Finally, we check whether the fold resulted in any phases. If not, we have a NonExistent timeline. Otherwise we reverse the phases and return a Timeline that is Existent.

Create-update-delete-based Timeline

In this variant, we first need to partition the events into two buckets: events with an effective timestamp, and events without. Mapping to an array proved to be faster in benchmarks.

Events without an effective timestamp are then sorted by their application timestamp.

Events with an effective timestamp are sorted primarily by their effective timestamp, then by their application timestamp, and by their kind as a decider. This makes sure that events with the same effective and application are sorted in a meaningful way (create before update before delete).

The applyEventsWithoutEffective is used during the projection to apply the ModifyPerpetually events, which change the values in every phase given their application timestamp is later than the event (with effective timestamp) currently projected.

The folder function loops over the event with an effective timestamp and creates phases based on the interpretation of the event given by the configuration. When a phase is created, the applyEventsWithoutEffective function is called to get the final value for that phase. The “state” value of the folder function keeps track of the created phases, and the current projection.

The current projection is finally used to determine which kind of timeline we return. Again, we need to reverse the phases because we built them in reverse order (faster).

Projection Functions

To complete the module, we provide several variants of how events are projected into timelines: as a Map, a IReadOnlyDictionary, or as a list. Maps are better to perform further transformations, dictionaries are faster, and a list is sometimes easier to handle.

The grouper function is used to determine the individual event streams in the list of the events. Every event stream results in a timeline.

Benchmark

The projection should be fast, so we used a Benchmark.Net benchmark to optimise the code. We run some typical scenarios in our system.

Pretty fast. 😊

Summary

A couple of lines of code are at the heart of our system and run a couple of thousand times per second. We chose a custom-built way to project events for two reasons. When we started with event sourcing, there were no .NET libraries available. And over the years, we realised that we have some special requirements – I explained them over the course of this blog post series – that can be dealt with more easily with a custom solution than with the libraries available nowadays.

If you ask me whether you should build your own projectors (and infrastructure code to store events) or choose an existing library, I can’t aswer this question for you. However, I can give you a list of question that you should answer before making a choice:

  • How flexible are you in choosing a database (some libaries are bound to a certain database)?
  • Are bi-temporal events common in your domain?
  • Are you working on a long running product or in rather short lived projects?

With that, I consider this blog post series finished. Thanks for reading along.

Read the whole story
alvinashcraft
1 minute ago
reply
Pennsylvania, USA
Share this story
Delete

What’s new in .NET 11 Numerics

1 Share
November 17, 2026 9 minutes read

What's new in .NET 11 numerics: Decimal32/64/128, BFloat16, Complex<T>, Tensor<T> and TryParsePartial

.NET 11 numerics got a lot of love this year. The release adds three IEEE 754 decimal types, a BFloat16 type for AI workloads, a generic Complex<T>, generic random number APIs and a new partial parsing API. On top of that, System.Numerics.Tensors became much faster and stricter about correctness.

.NET 11 Numerics at a Glance

  • Decimal32, Decimal64 and Decimal128: base 10 floating-point types that follow IEEE 754, with 7, 16 and 34 significant digits.
  • BFloat16: a 16-bit float with the exponent range of float, popular in machine learning.
  • Complex<T>: complex numbers over float, double, Half, Decimal128 and other IEEE 754 types.
  • Random.NextInteger<T> and Random.NextBinaryFloat<T>: random values of any integer or binary floating-point type, such as UInt128, BigInteger or Half.
  • TryParsePartial: parses the number at the start of a text, then tells you how many characters it consumed.
  • System.Numerics.Tensors 11.0: layout-aware fast paths, plus fixes for overlapping buffers and NaN handling.

All these types live in the core libraries, so a project that targets net11.0 needs nothing else. Tensors are the exception, since they ship as a NuGet package:

<TargetFramework>net11.0</TargetFramework>
...
<PackageReference Include="System.Numerics.Tensors" Version="11.0.0" />

Decimal32, Decimal64 and Decimal128: IEEE 754 Decimal Types in .NET 11

Most .NET developers know two families of non-integer types. On one side, float and double follow IEEE 754 and work in base 2. Every value they hold is a multiple of a power of two. That explains why 0.1 + 0.2 == 0.3 returns false in C#. On the other side, System.Decimal works in base 10, so 0.1 is exact.

Why System.Decimal Was Not Enough

System.Decimal is a Microsoft-specific format. It comes from the DECIMAL type of Win32 and OLE Automation, and its designers had money in mind. It packs a 96-bit integer and a scale into 128 bits, which gives 28 to 29 significant digits. That works great for invoices.

Scientific code is another story. There is no NaN, no infinity and no signed zero. Also, System.Math offers no Sin, Cos or Sqrt overload for decimal.

The three new types fill that gap. They implement the base 10 formats of the IEEE 754 standard, and they plug into .NET generic math (initially released with .NET 7 in November 2022) just like double does. As a result, you get the full toolbox: Sqrt, Exp, Log, trigonometry, FusedMultiplyAdd and so on.

Type Size Significant digits Max value
System.Numerics.Decimal32 32 bits 7 9.999999E+96
System.Numerics.Decimal64 64 bits 16 9.999999999999999E+384
System.Numerics.Decimal128 128 bits 34 9.99…9E+6144 (34 nines)
System.Decimal (decimal) 128 bits 28 to 29 about 7.9E+28
System.Double (double) (base 2) 64 bits 15 to 17 about 1.8E+308

Picking a size is a trade-off between storage and precision. Decimal32 suits large arrays of sensor values where 7 digits are plenty. Decimal64 is the natural pick when you want a double that thinks in base 10. Finally, Decimal128 beats System.Decimal on precision at the same 128-bit size.

For interop with databases or native libraries, EncodeDecimal() and EncodeBinary() return the two bit layouts that IEEE 754 defines: densely packed decimal and binary integer decimal.

0.1 Is Finally Exact

Let’s start with the classic rounding problem. The code below adds ten cents ten times, first with double, then with Decimal64:

using System.Globalization;
using System.Numerics;

var inv = CultureInfo.InvariantCulture;

double total = 0;
Decimal64 exactTotal = Decimal64.Zero;
Decimal64 tenCents = Decimal64.Parse("0.10", inv);

for (int i = 0; i < 10; i++) {
   total += 0.10;
   exactTotal += tenCents;
}

Console.WriteLine(total.ToString("R"));          // 0.9999999999999999
Console.WriteLine(exactTotal);                   // 1.00
Console.WriteLine(total == 1.0);                 // False
Console.WriteLine(exactTotal == Decimal64.One);  // True

The double total misses 1 by one unit in the last place. In contrast, the Decimal64 total is exact. Also look closely at the output: it prints 1.00 and not 1. The value remembers that its inputs carried two decimal places. That brings us to the most original concept of these types.

Quantum: Why 2.5 and 2.500 Are Not the Same Value

In IEEE 754 decimal arithmetic, every value has a coefficient and an exponent. The exponent defines the quantum of the value, which is the size of one unit in its last digit. Two values can compare equal and still carry different quanta.

Why should you care? Think about a mechanical drawing. A shaft labeled 2.5 mm and a shaft measured at 2.500 mm have the same nominal size. Yet the second figure promises a tolerance a hundred times tighter. Trailing zeros carry information, and the new types keep it:

Decimal64 nominal  = Decimal64.Parse("2.5", inv);    // drawing says 2.5 mm
Decimal64 measured = Decimal64.Parse("2.500", inv);  // caliper says 2.500 mm

Console.WriteLine(nominal == measured);                           // True
Console.WriteLine(Decimal64.HaveSameQuantum(nominal, measured));  // False
Console.WriteLine(Decimal64.GetQuantum(nominal));                 // 0.1
Console.WriteLine(Decimal64.GetQuantum(measured));                // 0.001

Console.WriteLine(nominal * measured);   // 6.2500
Console.WriteLine(measured + 1);         // 3.500

To be fair, System.Decimal keeps trailing zeros too, so 2.5m and 2.500m print differently. However, no formal rule says how that scale flows through arithmetic, and no API lets you inspect or compare it. With the IEEE types, the standard defines the rules. For example, a product adds the exponents of its operands, hence 6.2500. Similarly, a sum keeps the finer quantum, hence 3.500.

Rounding to a Quantum with Quantize

Quantize() rounds a value so that it takes the quantum of a second value. That makes it the natural tool to round a price to the cent:

Decimal64 cent = Decimal64.Parse("0.01", inv);

foreach (string price in new[] { "19.987", "2.675", "2.665", "4.2" }) {
   Decimal64 value = Decimal64.Parse(price, inv);
   Console.WriteLine($"{price} -> {Decimal64.Quantize(value, cent)}");
}
// 19.987 -> 19.99
// 2.675 -> 2.68
// 2.665 -> 2.66
// 4.2 -> 4.20

Ties go to the even digit, which is the default rounding rule of IEEE 754 (also known as banker’s rounding). That is why 2.665 becomes 2.66. Also note that Quantize() pads 4.2 into 4.20, which comes in handy before you format a column of prices.

Infinity, NaN and Signed Zero

The new types follow the IEEE semantics for special values. In particular, dividing by zero does not throw. Instead, it returns an infinity whose sign depends on the sign of the zero:

Decimal64 zero = Decimal64.Zero;

Console.WriteLine(Decimal64.One / zero);                    // Infinity
Console.WriteLine(Decimal64.One / Decimal64.NegativeZero);  // -Infinity
Console.WriteLine(zero / zero);                             // NaN
Console.WriteLine(Decimal64.Sqrt(Decimal64.NegativeOne));   // NaN

decimal legacyZero = 0m;
try {
   Console.WriteLine(1m / legacyZero);
} catch (DivideByZeroException) {
   Console.WriteLine("System.Decimal throws");               // System.Decimal throws
}

// 34 significant digits, with the full math toolbox
Console.WriteLine(Decimal128.Sqrt(2));       // 1.414213562373095048801688724209698
Console.WriteLine(Decimal128.One / 3);       // 0.3333333333333333333333333333333333
Console.WriteLine(decimal.One / 3m);         // 0.3333333333333333333333333333
Console.WriteLine(Decimal128.Cos(Decimal128.Pi));  // -1.000000000000000000000000000000000

This behavior may surprise developers used to System.Decimal, yet it makes mathematical sense. In floating-point code, a zero often stands for a tiny result that rounding pushed down to zero. As a divisor approaches zero, the quotient approaches infinity, and the sign of the zero tells you from which side. Signed zero matters a lot in scientific code, for example with complex numbers.

Trap: Don’t Build Decimal Values from Double Literals

C# has no literal suffix for the new types. Integers convert implicitly, so Decimal64 five = 5; compiles fine. For fractional values, though, resist the temptation to write CreateChecked(0.1):

Console.WriteLine(Decimal64.CreateChecked(0.1));   // 0.1000000000000000
Console.WriteLine(Decimal128.CreateChecked(0.1));  // 0.1000000000000000055511151231257827
Console.WriteLine(Decimal64.CreateChecked(0.1m));  // 0.1
Console.WriteLine(Decimal64.Parse("0.1", inv));    // 0.1

The literal 0.1 is a double, so it already holds the binary rounding error. Decimal128 has enough digits to show that error in full. Decimal64 hides it, but the value still ends up with a 16-digit quantum instead of 0.1. So parse a string, or start from a decimal literal like 0.1m.

BFloat16: The Range of float in 16 Bits

Unlike the decimal types, BFloat16 does not come from IEEE. Google designed it for its machine learning hardware, and the name stands for brain floating point. The idea is simple: take a 32-bit float and keep only its upper 16 bits. You keep the sign bit and all 8 exponent bits, but only 7 of the 23 fraction bits survive.

Compare that with Half, the other 16-bit floating-point type of .NET:

Type Sign bits Exponent bits Fraction bits Max value
Half 1 5 10 65,504
BFloat16 1 8 7 about 3.39E+38
float 1 8 23 about 3.40E+38

In short, Half favors precision near one, while BFloat16 favors range. The code below shows both sides of that trade-off:

float large = 100_000f;
Console.WriteLine((Half)large);              // Infinity
Console.WriteLine((float)(BFloat16)large);   // 99840

float nearOne = 1.001f;
Console.WriteLine((Half)nearOne);            // 1.001
Console.WriteLine((BFloat16)nearOne);        // 1

// 2 bytes per weight instead of 4
float[] weights = [0.123456f, -2.5f, 3.14159f, 70_000f];
BFloat16[] packed = Array.ConvertAll(weights, w => (BFloat16)w);
// Widened back to float: 0.123535156, -2.5, 3.140625, 70144

Half cannot hold 100,000, so it overflows to infinity. BFloat16 holds it, at the cost of a coarse step: the nearest value is 99,840. In the other direction, BFloat16 rounds 1.001 to 1, since 7 fraction bits cannot see a 0.1% difference.

So why would anyone accept that? Because neural network weights tolerate low precision, but they hate overflow. Moreover, conversions between float and BFloat16 are cheap, since both types share the same exponent layout. You halve memory and bandwidth, and your values keep the range of float. For training and inference code, that is often the right deal.

Complex<T> and Generic Math

For years, System.Numerics.Complex only supported double. Developers kept asking for float, mostly for signal processing. Generic math finally made a clean answer possible. Thus .NET 11 adds Complex<T>, where T can be any type that implements IFloatingPointIeee754<T> and IMinMaxValue<T>.

That covers float, double, Half, BFloat16 and the three decimal types. Along the way, the team also aligned edge-case behavior with the standard rules for complex arithmetic.

Better still, Complex<T> implements INumberBase<Complex<T>> itself. So any algorithm written against INumberBase<T> runs on complex numbers too. Here is a polynomial evaluator based on Horner’s method:

// Evaluates c0 + c1*x + c2*x^2 + ...
static T Polynomial<T>(ReadOnlySpan<int> coefficients, T x) where T : INumberBase<T> {
   T result = T.Zero;
   for (int i = coefficients.Length - 1; i >= 0; i--) {
      result = result * x + T.CreateChecked(coefficients[i]);
   }
   return result;
}

int[] p = [1, -2, 1];   // p(x) = 1 - 2x + x^2, which is (x - 1)^2

Console.WriteLine(Polynomial(p, 1.1));                            // 0.010000000000000009
Console.WriteLine(Polynomial(p, Decimal64.Parse("1.1", inv)));    // 0.010
Console.WriteLine(Polynomial(p, (BFloat16)3f));                   // 4
Console.WriteLine(Polynomial(p, new Complex<float>(1, 1)));       // <-1; 0>
Console.WriteLine(Polynomial(p, new Complex<Decimal128>(1, 1)));  // <-1; 0>

One method, five numeric types, zero copy-paste. Look at the first two lines: (1.1 – 1)² should give 0.01. While double returns 0.010000000000000009, Decimal64 returns an exact 0.010. Then for the complex input 1 + i, the result is i², which is -1.

Why the .NET Team Bets on Generic Math

The .NET team uses the same technique inside the base class library. Every numeric feature has to work across a long list of types: byte, sbyte, short, ushort, int, uint, long, ulong, nint, nuint, Half, float, double, decimal, the new decimal types, their complex versions and more. Generic math also lets the team share code between the scalar, vector and tensor APIs.

According to the session, this approach shrank some of these algorithms from several thousand lines to a few hundred. If you maintain a numeric library, that argument alone should convince you to look at static abstract members, the C# feature behind generic math.

New to generic math? Then read our article The .NET Generic Math Library first. It explains how static abstract members make T.Zero and a + b legal in generic code. It also tours the fine-grained interfaces such as INumberBase<T> and IFloatingPointIeee754<T>, which the new types of .NET 11 implement. Finally, it shows why generic methods over numeric structs avoid boxing.

System.Numerics.Tensors in .NET 11

What a Tensor Is

A tensor is not an AI invention. Numeric libraries have handled shaped data for about 40 years, long before anybody called it a tensor. The idea builds on what you already know. A float is a scalar. Then a Span<float> or an array is a linear sequence of scalars.

A tensor adds a shape on top of such data: a number of dimensions, a length for each dimension, and a stride for each dimension. The stride says how far apart two neighbors sit in memory. With strides, a tensor can describe gaps and non-linear slices without copying anything. Image processing relies on this a lot, because bitmaps often pad each row.

On the .NET side, TensorPrimitives shipped in .NET 8. Then the Tensor<T> family arrived as an experimental API in .NET 9 and became stable in .NET 10. Now .NET 11 makes it faster and more correct.

A Strided View over a Padded Buffer

The sample below describes a 3×2 grayscale image. Each row holds two pixels followed by two padding values, so the row stride is 4:

using System.Numerics.Tensors;

float[] buffer = [
   0.1f, 0.5f, -1f, -1f,   // row 0 + padding
   0.9f, 0.3f, -1f, -1f,   // row 1 + padding
   0.7f, 0.2f              // row 2
];
var image = new ReadOnlyTensorSpan<float>(buffer, lengths: [3, 2], strides: [4, 1]);

Console.WriteLine(image.IsDense);           // False
Console.WriteLine(image.FlattenedLength);   // 6
Console.WriteLine(image[1, 0]);             // 0.9

Span<float> pixels = stackalloc float[(int)image.FlattenedLength];
image.FlattenTo(pixels);                    // 0.1, 0.5, 0.9, 0.3, 0.7, 0.2

Console.WriteLine(Tensor.Max(image));         // 0.9
Console.WriteLine(Tensor.IndexOfMax(image));  // 2

IsDense returns false because the rows are not contiguous in memory. Then FlattenTo() walks the shape and skips the padding. Reductions such as Max() and IndexOfMax() respect the layout as well. Note that IndexOfMax() returns an index in the flattened view, not in the raw buffer.

Tensor Performance: Over 100x Faster on Dense Adds

The .NET team reworked a few core routines that walk tensor memory. Those routines now find the longest contiguous runs in a shape and process them with vectorized code. Because the whole tensor API builds on these routines through generic math, the speedup lights up everywhere. The session showed these numbers:

Operation (64×16 floats) Before .NET 11 Speedup
Dense Add 16.37 µs 0.114 µs about 144x
FlattenTo with gapped rows 7.92 µs 0.875 µs about 9x

The team ran these benchmarks on a Ryzen 9 7950X under Windows x64. Both columns use the same .NET 11 runtime: only the tensor assemblies differ.

Correctness First: Overlapping Buffers

Fast code is worthless if it returns a wrong result. While adding the fast paths, the team found cases where the source and the destination shared memory with an offset. In those cases, the old code could produce wrong data. Now .NET 11 handles dense overlap correctly and rejects layouts it cannot copy safely:

// Dense overlap: shift the samples right by one slot
int[] samples = [10, 20, 30, 40, 50];
ReadOnlyTensorSpan<int> source = new(samples.AsSpan(0, 4));
TensorSpan<int> destination = new(samples.AsSpan(1, 4));
source.CopyTo(destination);
Console.WriteLine(string.Join(", ", samples));   // 10, 10, 20, 30, 40

// Strided overlap: read every other value into a region that overlaps it
int[] data = [1, 2, 3, 4, 5, 6];
ReadOnlyTensorSpan<int> everyOther = new(data, [3], [2]);   // 1, 3, 5
TensorSpan<int> target = new(data.AsSpan(1, 3));
try {
   everyOther.CopyTo(target);
} catch (ArgumentException) {
   Console.WriteLine(string.Join(", ", data));   // 1, 2, 3, 4, 5, 6
}

The first copy behaves like Span<T>.CopyTo(): the data shifts right by one slot, as expected. The second copy reads every other element from a buffer that it overwrites at the same time. Supporting it safely would need a temporary copy. Therefore .NET 11 throws an ArgumentException and leaves the buffer untouched. In my opinion that’s the right call, since a loud exception beats silent corruption.

NaN, Ties and Older Hardware

Tensors also get the search helpers you know from Span<T> and TensorPrimitives: IndexOfMax(), IndexOfMin(), IndexOfMaxMagnitude() and IndexOfMinMagnitude(). Their rules match the scalar Max() and Min() methods:

float[] readings = [2.5f, float.NaN, 7.1f, 7.1f];
Console.WriteLine(Tensor.IndexOfMax(new ReadOnlyTensorSpan<float>(readings)));  // 1

float[] ties = [2.5f, 7.1f, 1f, 7.1f];
Console.WriteLine(Tensor.IndexOfMax(new ReadOnlyTensorSpan<float>(ties)));      // 1

NaN propagates, so IndexOfMax() returns the position of the first NaN. Without NaN, a tie resolves to the first occurrence.

Finally, the team double-checked accuracy on older CPUs. Most processors from the last 15 years support fused multiply-add (FMA), which computes a * b + c with a single rounding. Some machines still lack it, and .NET 11 makes sure they get the same accurate results.

Generic Random Numbers: NextInteger<T> and NextBinaryFloat<T>

Until now, System.Random offered Next(), NextInt64(), NextDouble(), NextSingle() and not much more. If you needed a random UInt128, a BigInteger below some bound or a random Half, you had to build it from raw bytes. Getting a uniform distribution that way is trickier than it looks.

.NET 11 adds two generic methods. NextInteger<T>() works with any IBinaryInteger<T>, while NextBinaryFloat<T>() works with any IBinaryFloatingPointIeee754<T>:

var rng = new Random(2026);

UInt128 id         = rng.NextInteger(UInt128.One << 100);      // [0, 2^100)
BigInteger huge    = rng.NextInteger(BigInteger.Pow(10, 40));  // [0, 10^40)
int die            = rng.NextInteger(1, 7);                    // 1 to 6
BFloat16 weight    = rng.NextBinaryFloat<BFloat16>();          // [0, 1)
Half noise         = rng.NextBinaryFloat<Half>();              // [0, 1)

The bounds follow the same rules as Next(): the lower bound is inclusive, and the upper bound is exclusive. Floating-point results fall in [0, 1). Because of the generic constraint, NextBinaryFloat<T>() accepts float, double, Half and BFloat16, but not the decimal types.

Keep in mind that these are not cryptographic APIs. They offer the same pseudo-random guarantees as the rest of System.Random. For tokens, keys or anything security related, use RandomNumberGenerator from System.Security.Cryptography instead.

Partial Parsing with TryParsePartial

Real-world text rarely contains a bare number. You get "12.5ms", "3GB" or a CSV line. Until now, you first had to scan for the end of the number, slice it, and only then call TryParse(). The new TryParsePartial() method does it in one pass. It parses up to the first character that cannot belong to the number, then reports how many characters it consumed.

static (double Value, string Unit) ParseQuantity(string text) {
   if (!double.TryParsePartial(text, NumberStyles.Float, CultureInfo.InvariantCulture,
                               out double value, out int consumed)) {
      throw new FormatException($"'{text}' does not start with a number.");
   }
   return (value, text[consumed..]);
}

foreach (string text in new[] { "12.5ms", "-0.25 dB", "1e3Hz", "3em" }) {
   var (value, unit) = ParseQuantity(text);
   Console.WriteLine($"{value} [{unit}]");
}
// 12.5 [ms]
// -0.25 [dB]
// 1000 [Hz]
// 3 [em]

Two details are worth knowing here. First, NumberStyles.Float allows trailing white space, so the space before dB counts as consumed. Second, the parser does not mistake the e of em for an exponent, because no digit follows it.

Partial Parsing in Generic Code

TryParsePartial() exists on every numeric type of the base class library, including the new ones. It also sits on INumberBase<T>, so it works in generic code as well. For example, the loop below walks a semicolon-separated line with no Split() call and no substring allocation:

ReadOnlySpan<char> line = "4.5;12;0.75;8";
Decimal64 sum = Decimal64.Zero;

while (!line.IsEmpty) {
   if (!Decimal64.TryParsePartial(line, NumberStyles.Float, inv, out Decimal64 value, out int used)) {
      throw new FormatException($"Bad field at: {line}");
   }
   sum += value;
   line = line[used..];
   if (!line.IsEmpty && line[0] == ';') { line = line[1..]; }
}
Console.WriteLine(sum);   // 25.25

This pattern fits CSV readers, JSON tokenizers and any format with delimiters, since you skip the extra pass that finds where each number ends. Overloads also accept UTF-8 bytes. Speaking of UTF-8, BigInteger now implements IUtf8SpanParsable<T> and IUtf8SpanFormattable. As a consequence, you can parse and format big integers straight from and to byte buffers:

BigInteger big = BigInteger.Parse("123456789012345678901234567890"u8, inv);

Span<byte> utf8 = stackalloc byte[64];
big.TryFormat(utf8, out int written, default, inv);   // written: 30

.NET 11 Numerics FAQ

What are Decimal32, Decimal64 and Decimal128 in .NET 11?

They are base 10 floating-point types that implement the IEEE 754 decimal formats. They offer 7, 16 and 34 significant digits. Like double, they support NaN, infinity, signed zero and the full set of math functions through generic math.

What is the difference between Decimal64 and System.Decimal?

System.Decimal is a Microsoft-specific, currency-oriented format with 28 to 29 digits and no NaN or infinity. Decimal64 follows IEEE 754, defines how the quantum of a value flows through arithmetic, and supports functions such as Sqrt, Exp and Sin.

What is the quantum of a decimal value?

The quantum is the size of one unit in the last digit of a value. For example, 2.5 has a quantum of 0.1 and 2.500 has a quantum of 0.001. Both compare equal, but HaveSameQuantum returns false for them.

What is BFloat16 used for?

BFloat16 stores numbers in 16 bits with the same exponent range as float. Machine learning code uses it to halve memory and bandwidth for weights and activations without risking overflow.

What is the difference between BFloat16 and Half?

Both types use 16 bits. Half has 5 exponent bits and 10 fraction bits, so it is more precise near one but overflows above 65,504. BFloat16 has 8 exponent bits and 7 fraction bits, so it covers the whole range of float with less precision.

Can I use Complex<T> with float?

Yes. In .NET 11, Complex<T> accepts any T that implements IFloatingPointIeee754<T> and IMinMaxValue<T>, such as float, double, Half, BFloat16 or Decimal128. The older Complex type still exists and only supports double.

Is Random.NextInteger<T> cryptographically secure?

No. NextInteger<T> and NextBinaryFloat<T> offer the same pseudo-random guarantees as the rest of System.Random. Use RandomNumberGenerator for security-sensitive values.

Do I need a NuGet package for the new numeric types?

No for Decimal32, Decimal64, Decimal128, BFloat16, Complex<T>, the new Random methods and TryParsePartial: they ship in .NET 11 itself. Only the tensor types need the System.Numerics.Tensors package.

Conclusion

.NET 11 numerics is one of those updates that looks modest in the release notes and feels big once you start using it. The IEEE decimal types finally give .NET a base 10 type built for science and engineering, not only for money. BFloat16 speaks the language of AI hardware. Meanwhile, Complex<T>, the generic Random methods and TryParsePartial() show how much generic math pays off a few releases after its debut.

Our advice is simple. Reach for Decimal64 or Decimal128 when trailing zeros or exact base 10 results matter, and keep System.Decimal for plain currency code. Upgrade System.Numerics.Tensors to 11.0 even if you never touch the new types, because the speed and correctness fixes come for free.

To go further, read our guides on .NET generic math, the IParsable interface and Span<T> performance. They explain the building blocks that most of these new APIs rely on.

The post What’s new in .NET 11 Numerics appeared first on NDepend Blog.

Read the whole story
alvinashcraft
1 minute ago
reply
Pennsylvania, USA
Share this story
Delete
Next Page of Stories