diff --git a/DotNetCampus.Numerics/FloatingPointHelper.cs b/DotNetCampus.Numerics/FloatingPointHelper.cs index 70ad5dd..81ebfcc 100644 --- a/DotNetCampus.Numerics/FloatingPointHelper.cs +++ b/DotNetCampus.Numerics/FloatingPointHelper.cs @@ -66,5 +66,24 @@ public static TNum Sqrt(this TNum a) throw new NotSupportedException(); } + public static TNum Clamp(this TNum value, TNum min, TNum max) + where TNum : unmanaged, IFloatingPoint + { + if (typeof(TNum) == typeof(float)) + return Unsafe.BitCast(Math.Clamp(Unsafe.BitCast(value), Unsafe.BitCast(min), Unsafe.BitCast(max))); + + if (typeof(TNum) == typeof(double)) + return Unsafe.BitCast(Math.Clamp(Unsafe.BitCast(value), Unsafe.BitCast(min), Unsafe.BitCast(max))); + + if (typeof(TNum) == typeof(NFloat)) + return Unsafe.BitCast(NFloat.Clamp(Unsafe.BitCast(value), Unsafe.BitCast(min), Unsafe.BitCast(max))); + + return value <= min + ? min + : value >= max + ? max + : value; + } + #endregion } diff --git a/DotNetCampus.Numerics/FloatingPointNumberExtensions.cs b/DotNetCampus.Numerics/FloatingPointNumberExtensions.cs index dc0dcce..23eca56 100644 --- a/DotNetCampus.Numerics/FloatingPointNumberExtensions.cs +++ b/DotNetCampus.Numerics/FloatingPointNumberExtensions.cs @@ -1,3 +1,5 @@ +using System.Runtime.Intrinsics.Arm; + namespace DotNetCampus.Numerics; /// @@ -84,6 +86,7 @@ public static int Round(this float value) /// 四舍五入到整数。 public static int RoundingHalfAwayFromZero(this double value) { + return (int)Math.Round(value, MidpointRounding.AwayFromZero); } @@ -97,6 +100,26 @@ public static int RoundingHalfAwayFromZero(this float value) return (int)MathF.Round(value, MidpointRounding.AwayFromZero); } + /// + /// 对浮点数进行五舍六入。 + /// + /// 要进行五舍六入的浮点数。 + /// 五舍六入到整数。 + public static int RoundingHalfToZero(this double value) + { + return (int)Math.Truncate(value - Math.CopySign(0.5, value)); + } + + /// + /// 对浮点数进行五舍六入。 + /// + /// 要进行五舍六入的浮点数。 + /// 五舍六入到整数。 + public static int RoundingHalfToZero(this float value) + { + return (int)MathF.Truncate(value - MathF.CopySign(0.5f, value)); + } + /// /// 对浮点数进行向下取整。 /// @@ -281,4 +304,4 @@ public static double Pow(this float value, double exponent) } #endregion -} \ No newline at end of file +} diff --git a/DotNetCampus.Numerics/Interval.cs b/DotNetCampus.Numerics/Interval.cs index 2e4e53b..dcb5de3 100644 --- a/DotNetCampus.Numerics/Interval.cs +++ b/DotNetCampus.Numerics/Interval.cs @@ -67,6 +67,16 @@ public bool Contains(TNum value) return Start <= value && value <= End; } + /// + /// 将目标值限制在区间内。 + /// + /// 需要限制的值。 + /// 限制后的值。 + public TNum Clamp(ref TNum value) + { + return value.Clamp(Start, End); + } + /// public override string ToString() {