Consider updating Math.Clamp to not throw when min is greater than max

Open
#119,256 7 comments 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
5/5
Estimated time
Over a week
Newbie friendliness
35/100
Issue type
Feature
Clarity
Mostly clear
Activity status
Stale
Tech stack
csharp
Domain
backend

Research direction

Start with the Math.Clamp APIs named in the issue and review the linked discussion for the proposed semantics. Compare the existing behavior with the vector APIs mentioned, then identify the relevant implementation and tests. Done means the behavior for correctly ordered and swapped min/max values is explicitly decided and covered consistently.

Written by the indexing model from the issue text.

Description

area-System.Numerics

As noted by @tannergooding:

It's pretty typical for Clamp APIs to follow a well-specified order for mismatched min/max, as it's far more efficient and is useful for a number of scenarios. -- We end up doing just this for the vector APIs and it correspondingly can bleed into other scenarios, like Tensors

The typical behavior is Min(Max(value, min), max) which matches what hardware typically does for such instructions, what HLSL and GLSL do, etc. -- Effectively this returns max if min/max are incorrectly ordered.

Default behavior (min/max are correctly ordered)
value min max result
1 2 3 2
2 1 3 2
3 1 2 2
Swapped behavior (Min(Max(value, min), max))
value min max result
1 3 2 2
2 3 1 1
3 2 1 1
Swapped behavior (Max(Min(value, max), min))
value min max result
1 3 2 3
2 3 1 3
3 2 1 2

Originally posted by @tannergooding in https://github.com/dotnet/runtime/pull/118824#discussion_r2282953148

Dominant language
C#
Stars
18.3k
Forks
5.6k
PR merge metrics
PR metrics pending

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from dotnet/runtime

All issues in dotnet/runtime

Similar issues

More C# issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.