Skip to content

Commit

Permalink
添加区间的 Clamp 方法
Browse files Browse the repository at this point in the history
  • Loading branch information
SeWZC committed Jan 10, 2025
1 parent b724dce commit 73beb72
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
19 changes: 19 additions & 0 deletions DotNetCampus.Numerics/FloatingPointHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -66,5 +66,24 @@ public static TNum Sqrt<TNum>(this TNum a)
throw new NotSupportedException();
}

public static TNum Clamp<TNum>(this TNum value, TNum min, TNum max)
where TNum : unmanaged, IFloatingPoint<TNum>
{
if (typeof(TNum) == typeof(float))
return Unsafe.BitCast<float, TNum>(Math.Clamp(Unsafe.BitCast<TNum, float>(value), Unsafe.BitCast<TNum, float>(min), Unsafe.BitCast<TNum, float>(max)));

if (typeof(TNum) == typeof(double))
return Unsafe.BitCast<double, TNum>(Math.Clamp(Unsafe.BitCast<TNum, double>(value), Unsafe.BitCast<TNum, double>(min), Unsafe.BitCast<TNum, double>(max)));

if (typeof(TNum) == typeof(NFloat))
return Unsafe.BitCast<NFloat, TNum>(NFloat.Clamp(Unsafe.BitCast<TNum, NFloat>(value), Unsafe.BitCast<TNum, NFloat>(min), Unsafe.BitCast<TNum, NFloat>(max)));

return value <= min
? min
: value >= max
? max
: value;
}

#endregion
}
10 changes: 10 additions & 0 deletions DotNetCampus.Numerics/Interval.cs
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,16 @@ public bool Contains(TNum value)
return Start <= value && value <= End;
}

/// <summary>
/// 将目标值限制在区间内。
/// </summary>
/// <param name="value">需要限制的值。</param>
/// <returns>限制后的值。</returns>
public TNum Clamp(ref TNum value)
{
return value.Clamp(Start, End);
}

/// <inheritdoc />
public override string ToString()
{
Expand Down

0 comments on commit 73beb72

Please sign in to comment.