Skip to content

Add Complex<T> generic struct mirroring Complex API surface - #130414

Merged
tannergooding merged 11 commits into
mainfrom
copilot/sub-pr-127331
Jul 9, 2026
Merged

tannergooding merged 11 commits into
mainfrom
copilot/sub-pr-127331

Conversation

@tannergooding

Copy link
Copy Markdown
Member

Implements a generic Complex<T> where T : IFloatingPointIeee754<T>, IMinMaxValue<T> that mirrors the full public API of the existing Complex struct, as scoped by @tannergooding. The IComplexNumber<TSelf, T> interface and new members on non-generic Complex are deferred to a follow-up PR.

Description

New type: Complex<T>

Direct generic port of Complex in a new Complex.Generic.cs source file:

  • Arithmetic operators: all Complex<T>×Complex<T>, T×Complex<T>, and Complex<T>×T overloads for +, -, *, /, unary -/+, ++, --
  • Static properties: Zero, One, ImaginaryOne, NaN, Infinity (exposed as static properties per the approved API surface; INumberBase.One and INumberBase.Zero bind implicitly to the matching public properties)
  • Properties: Real, Imaginary
  • Instance methods: GetMagnitude(), GetPhase() (per approved API surface — exposed as named methods rather than properties)
  • Math: Abs, Conjugate, Reciprocal, Log/Log10, Exp, Sqrt, Pow, Sin/Cos/Tan, Sinh/Cosh/Tanh, Asin/Acos/Atan, FromPolarCoordinates
  • Predicates: full Is* set matching INumberBase<T>
  • Generic math: implements INumberBase<Complex<T>>, ISignedNumber<Complex<T>>, IAdditiveIdentity, IMultiplicativeIdentity, IEquality/Comparison operators
  • Parsing / formatting: full IParsable, ISpanParsable, IUtf8SpanParsable, ISpanFormattable, IUtf8SpanFormattable
  • Conversions: CreateChecked/CreateSaturating/CreateTruncating use internal TryConvertFrom*Core and TryConvertTo*Core helpers that correctly chain same-type, cross-type (Complex ↔ Complex<T>), BigInteger, and general numeric type special cases per mode

Constraint rationale

IMinMaxValue<T> is added alongside IFloatingPointIeee754<T> because the ported Sqrt and Asin_Internal algorithms compute per-instantiation overflow thresholds from T.MaxValue (e.g., s_sqrtRescaleThreshold, s_asinOverflowThreshold). Every practical floating-point type (float, double, Half, BFloat16, NFloat) implements both interfaces.

Shared constants

Complex.DefaultNumberStyle and Complex.InvalidNumberStyles are promoted from private to internal in Complex.cs so that Complex<T> can reference them directly rather than maintaining duplicate definitions.

Code sharing between Complex and Complex<T>

To ensure the non-generic Complex and Complex<T> stay in sync, all Complex methods with more than 4 lines of implementation now delegate to the corresponding Complex<double> method. This covers:

  • Mixed-type operators: operator *(Complex, double), operator *(double, Complex), and all three / overloads
  • Trig/math functions: Asin, Acos, Tan, Sqrt, Pow(Complex, Complex)
  • Magnitude comparisons: MaxMagnitude, MinMagnitude
  • Formatting: ToString(string?, IFormatProvider?)
  • Explicit interface implementations MaxMagnitudeNumber, MinMagnitudeNumber, MultiplyAddEstimate: each has an internal static implementation on Complex<T>; Complex<T>'s explicit interface implementation delegates to it, and Complex's explicit interface implementation calls through Complex<double>
  • Conversion helpers TryConvertFrom*: Complex<T> exposes internal static TryConvertFromCheckedCore, TryConvertFromSaturatingCore, TryConvertFromTruncatingCore that implement the full conversion logic (same-type, Complex→Complex<T>, signed types via T.TryConvertFrom*, unsigned/decimal types via TOther.TryConvertTo*<T>); Complex.TryConvertFrom replaces its long explicit type chain with a Complex<double> special case followed by delegation to Complex<double>.TryConvertFromCheckedCore
  • Conversion helpers TryConvertTo*: Complex<T> exposes internal static TryConvertToCheckedCore, TryConvertToSaturatingCore, TryConvertToTruncatingCore that implement the full conversion logic (same-type fast path returning real/NaN, Complex output via double.Create*, BigInteger output with appropriate imaginary-part handling, general types via T.TryConvertTo* with fallback to TOther.TryConvertFrom*<T>); Complex's three long TryConvertTo* chains are replaced with a Complex<double> output special case followed by delegation to Complex<double>.TryConvertTo*Core

As a result, the now-unused private fields (s_sqrtRescaleThreshold, s_asinOverflowThreshold, s_log2) and helpers (Log1P, Asin_Internal) are removed from Complex.cs.

Cross-type conversion support

Both types now correctly support bi-directional conversion:

  • Complex.CreateChecked(new Complex<double>(1, 2)) — Complex accepts Complex<double> input
  • Complex<float>.CreateChecked(new Complex(1, 2)) — Complex<T> accepts Complex (non-generic) input, with mode-appropriate component conversion
  • int.CreateChecked(new Complex<double>(5, 0)) — real types can be extracted from Complex<T> via TryConvertToCheckedCore
  • int.CreateChecked(new Complex(5, 0)) — real types can be extracted from Complex via delegation to Complex<double>.TryConvertToCheckedCore

Example usage

Complex<float> z = Complex<float>.FromPolarCoordinates(2.0f, MathF.PI / 4);
float mag   = z.GetMagnitude();
float phase = z.GetPhase();
Complex<float> w = z * 3.0f + new Complex<float>(1.0f, -1.0f);
var product = Complex<float>.Sin(z) * Complex<double>.Exp(new Complex<double>(0, Math.PI));

// Cross-type conversions work in both directions:
Complex        c  = Complex.CreateChecked(new Complex<double>(3, 4));
Complex<float> cf = Complex<float>.CreateChecked(new Complex(3, 4));
int            n  = int.CreateChecked(new Complex<double>(5, 0));

// Static properties:
var zero = Complex<float>.Zero;
var one  = Complex<double>.One;

Files changed

File Change
src/System/Numerics/Complex.cs Promote DefaultNumberStyle and InvalidNumberStyles to internal; delegate long methods to Complex<double>; replace TryConvertFrom/TryConvertTo* chains with Complex<double>.*Core delegation
src/System/Numerics/Complex.Generic.cs New — full Complex<T> implementation with static properties for Zero/One/ImaginaryOne/NaN/Infinity; GetMagnitude()/GetPhase() methods; internal static shared implementations for MaxMagnitudeNumber, MinMagnitudeNumber, MultiplyAddEstimate, TryConvertFrom*Core, and TryConvertTo*Core
src/System.Runtime.Numerics.csproj Add new file to build
ref/System.Runtime.Numerics.cs Add Complex<T> public surface to ref assembly
tests/ComplexTests.cs Add ComplexTests_Generic with 37 tests

Note

This PR description was authored by GitHub Copilot.

Copilot AI and others added 9 commits April 23, 2026 17:27
@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Tagging subscribers to this area: @dotnet/area-system-numerics
See info in area-owners.md if you want to be subscribed.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR adds a new public generic complex-number type System.Numerics.Complex<T> and updates the existing non-generic Complex implementation to delegate several operations/conversions to Complex<double>, along with adding initial unit test coverage for the generic type.

Changes:

  • Introduces new public Complex<T> implementation (Complex.Generic.cs) and wires it into the build.
  • Updates Complex to expose shared parsing styles internally and to delegate several operators/math/conversion paths to Complex<double>.
  • Extends tests with a new ComplexTests_Generic suite validating basic construction, arithmetic, parsing, predicates, and conversions.
Show a summary per file
File Description
src/libraries/System.Runtime.Numerics/src/System/Numerics/Complex.Generic.cs New Complex<T> implementation and generic-math/parsing/formatting/conversion helpers.
src/libraries/System.Runtime.Numerics/src/System/Numerics/Complex.cs Makes parse styles internal and redirects several Complex operations to Complex<double>.
src/libraries/System.Runtime.Numerics/src/System.Runtime.Numerics.csproj Includes the new Complex.Generic.cs in compilation.
src/libraries/System.Runtime.Numerics/ref/System.Runtime.Numerics.cs Adds the Complex<T> public surface to the ref assembly.
src/libraries/System.Runtime.Numerics/tests/ComplexTests.cs Adds ComplexTests_Generic coverage for Complex<T>.

Copilot's findings

  • Files reviewed: 5/5 changed files
  • Comments generated: 2

Copilot AI review requested due to automatic review settings July 9, 2026 16:22
@tannergooding

tannergooding commented Jul 9, 2026 •

Copy link
Copy Markdown
Member Author

This probably looks duplicative, and that's because it is. Turns out that copilot had #127333 target a random branch it created that wasn't main and so the code got merged and then almost immediately pruned, not actually making it into the product.

The PR is otherwise unchanged, aside from the merge commit and resolving the "conflicts" that occurred in the interim (namely the AllowInvalidTrailingCharacter support).

CC. @jeffhandley, @eiriktsarpalis

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot's findings

  • Files reviewed: 5/5 changed files
  • Comments generated: 2

@tannergooding
tannergooding enabled auto-merge (squash) July 9, 2026 19:17
@tannergooding
tannergooding merged commit 6c58491 into main Jul 9, 2026
89 of 90 checks passed
@tannergooding
tannergooding deleted the copilot/sub-pr-127331 branch July 9, 2026 19:44
@dotnet-milestone-bot dotnet-milestone-bot Bot added this to the 11.0-preview7 milestone Jul 10, 2026
eiriktsarpalis pushed a commit that referenced this pull request Jul 15, 2026
Implements a generic `Complex<T> where T : IFloatingPointIeee754<T>,
IMinMaxValue<T>` that mirrors the full public API of the existing
`Complex` struct, as scoped by @tannergooding. The
`IComplexNumber<TSelf, T>` interface and new members on non-generic
`Complex` are deferred to a follow-up PR.

## Description

### New type: `Complex<T>`

Direct generic port of `Complex` in a new `Complex.Generic.cs` source
file:

- **Arithmetic operators**: all `Complex<T>×Complex<T>`, `T×Complex<T>`,
and `Complex<T>×T` overloads for `+`, `-`, `*`, `/`, unary `-`/`+`,
`++`, `--`
- **Static properties**: `Zero`, `One`, `ImaginaryOne`, `NaN`,
`Infinity` (exposed as `static` properties per the approved API surface;
`INumberBase.One` and `INumberBase.Zero` bind implicitly to the matching
public properties)
- **Properties**: `Real`, `Imaginary`
- **Instance methods**: `GetMagnitude()`, `GetPhase()` (per approved API
surface — exposed as named methods rather than properties)
- **Math**: `Abs`, `Conjugate`, `Reciprocal`, `Log`/`Log10`, `Exp`,
`Sqrt`, `Pow`, `Sin`/`Cos`/`Tan`, `Sinh`/`Cosh`/`Tanh`,
`Asin`/`Acos`/`Atan`, `FromPolarCoordinates`
- **Predicates**: full `Is*` set matching `INumberBase<T>`
- **Generic math**: implements `INumberBase<Complex<T>>`,
`ISignedNumber<Complex<T>>`, `IAdditiveIdentity`,
`IMultiplicativeIdentity`, `IEquality/Comparison` operators
- **Parsing / formatting**: full `IParsable`, `ISpanParsable`,
`IUtf8SpanParsable`, `ISpanFormattable`, `IUtf8SpanFormattable`
- **Conversions**: `CreateChecked`/`CreateSaturating`/`CreateTruncating`
use `internal` `TryConvertFrom*Core` and `TryConvertTo*Core` helpers
that correctly chain same-type, cross-type (`Complex` ↔ `Complex<T>`),
`BigInteger`, and general numeric type special cases per mode

### Constraint rationale

`IMinMaxValue<T>` is added alongside `IFloatingPointIeee754<T>` because
the ported `Sqrt` and `Asin_Internal` algorithms compute
per-instantiation overflow thresholds from `T.MaxValue` (e.g.,
`s_sqrtRescaleThreshold`, `s_asinOverflowThreshold`). Every practical
floating-point type (`float`, `double`, `Half`, `BFloat16`, `NFloat`)
implements both interfaces.

### Shared constants

`Complex.DefaultNumberStyle` and `Complex.InvalidNumberStyles` are
promoted from `private` to `internal` in `Complex.cs` so that
`Complex<T>` can reference them directly rather than maintaining
duplicate definitions.

### Code sharing between `Complex` and `Complex<T>`

To ensure the non-generic `Complex` and `Complex<T>` stay in sync, all
`Complex` methods with more than 4 lines of implementation now delegate
to the corresponding `Complex<double>` method. This covers:

- Mixed-type operators: `operator *(Complex, double)`, `operator
*(double, Complex)`, and all three `/` overloads
- Trig/math functions: `Asin`, `Acos`, `Tan`, `Sqrt`, `Pow(Complex,
Complex)`
- Magnitude comparisons: `MaxMagnitude`, `MinMagnitude`
- Formatting: `ToString(string?, IFormatProvider?)`
- Explicit interface implementations `MaxMagnitudeNumber`,
`MinMagnitudeNumber`, `MultiplyAddEstimate`: each has an `internal
static` implementation on `Complex<T>`; `Complex<T>`'s explicit
interface implementation delegates to it, and `Complex`'s explicit
interface implementation calls through `Complex<double>`
- Conversion helpers `TryConvertFrom*`: `Complex<T>` exposes `internal
static TryConvertFromCheckedCore`, `TryConvertFromSaturatingCore`,
`TryConvertFromTruncatingCore` that implement the full conversion logic
(same-type, `Complex`→`Complex<T>`, signed types via
`T.TryConvertFrom*`, unsigned/decimal types via
`TOther.TryConvertTo*<T>`); `Complex.TryConvertFrom` replaces its long
explicit type chain with a `Complex<double>` special case followed by
delegation to `Complex<double>.TryConvertFromCheckedCore`
- Conversion helpers `TryConvertTo*`: `Complex<T>` exposes `internal
static TryConvertToCheckedCore`, `TryConvertToSaturatingCore`,
`TryConvertToTruncatingCore` that implement the full conversion logic
(same-type fast path returning real/NaN, `Complex` output via
`double.Create*`, `BigInteger` output with appropriate imaginary-part
handling, general types via `T.TryConvertTo*` with fallback to
`TOther.TryConvertFrom*<T>`); `Complex`'s three long `TryConvertTo*`
chains are replaced with a `Complex<double>` output special case
followed by delegation to `Complex<double>.TryConvertTo*Core`

As a result, the now-unused private fields (`s_sqrtRescaleThreshold`,
`s_asinOverflowThreshold`, `s_log2`) and helpers (`Log1P`,
`Asin_Internal`) are removed from `Complex.cs`.

### Cross-type conversion support

Both types now correctly support bi-directional conversion:

- `Complex.CreateChecked(new Complex<double>(1, 2))` — `Complex` accepts
`Complex<double>` input
- `Complex<float>.CreateChecked(new Complex(1, 2))` — `Complex<T>`
accepts `Complex` (non-generic) input, with mode-appropriate component
conversion
- `int.CreateChecked(new Complex<double>(5, 0))` — real types can be
extracted from `Complex<T>` via `TryConvertToCheckedCore`
- `int.CreateChecked(new Complex(5, 0))` — real types can be extracted
from `Complex` via delegation to
`Complex<double>.TryConvertToCheckedCore`

### Example usage

```csharp
Complex<float> z = Complex<float>.FromPolarCoordinates(2.0f, MathF.PI / 4);
float mag   = z.GetMagnitude();
float phase = z.GetPhase();
Complex<float> w = z * 3.0f + new Complex<float>(1.0f, -1.0f);
var product = Complex<float>.Sin(z) * Complex<double>.Exp(new Complex<double>(0, Math.PI));

// Cross-type conversions work in both directions:
Complex        c  = Complex.CreateChecked(new Complex<double>(3, 4));
Complex<float> cf = Complex<float>.CreateChecked(new Complex(3, 4));
int            n  = int.CreateChecked(new Complex<double>(5, 0));

// Static properties:
var zero = Complex<float>.Zero;
var one  = Complex<double>.One;
```

### Files changed

| File | Change |
|---|---|
| `src/System/Numerics/Complex.cs` | Promote `DefaultNumberStyle` and
`InvalidNumberStyles` to `internal`; delegate long methods to
`Complex<double>`; replace `TryConvertFrom`/`TryConvertTo*` chains with
`Complex<double>.*Core` delegation |
| `src/System/Numerics/Complex.Generic.cs` | New — full `Complex<T>`
implementation with `static` properties for
`Zero`/`One`/`ImaginaryOne`/`NaN`/`Infinity`;
`GetMagnitude()`/`GetPhase()` methods; `internal static` shared
implementations for `MaxMagnitudeNumber`, `MinMagnitudeNumber`,
`MultiplyAddEstimate`, `TryConvertFrom*Core`, and `TryConvertTo*Core` |
| `src/System.Runtime.Numerics.csproj` | Add new file to build |
| `ref/System.Runtime.Numerics.cs` | Add `Complex<T>` public surface to
ref assembly |
| `tests/ComplexTests.cs` | Add `ComplexTests_Generic` with 37 tests |

> [!NOTE]
> This PR description was authored by GitHub Copilot.

---------

Co-authored-by: copilot-swe-agent[bot] <[email protected]>
Co-authored-by: tannergooding <[email protected]>
@github-actions github-actions Bot locked and limited conversation to collaborators Aug 10, 2026

This branch had an error being deployed

1 failed deployment
copilot-pat-pool — 373c86bc Deployed Jul 9, 2026 by tannergooding via pre_activation #14255
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants