/
MathF.cs
574 lines (477 loc) · 19.4 KB
/
MathF.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// ===================================================================================================
// Portions of the code implemented below are based on the 'Berkeley SoftFloat Release 3e' algorithms.
// ===================================================================================================
using System.Diagnostics;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
using System.Runtime.Intrinsics.Arm;
namespace System
{
/// <summary>
/// Provides constants and static methods for trigonometric, logarithmic, and other common mathematical functions.
/// </summary>
public static partial class MathF
{
public const float E = 2.71828183f;
public const float PI = 3.14159265f;
public const float Tau = 6.283185307f;
private const int maxRoundingDigits = 6;
// This table is required for the Round function which can specify the number of digits to round to
private static ReadOnlySpan<float> RoundPower10Single => new float[] {
1e0f, 1e1f, 1e2f, 1e3f, 1e4f, 1e5f, 1e6f
};
private const float singleRoundLimit = 1e8f;
private const float SCALEB_C1 = 1.7014118E+38f; // 0x1p127f
private const float SCALEB_C2 = 1.1754944E-38f; // 0x1p-126f
private const float SCALEB_C3 = 16777216f; // 0x1p24f
private const int ILogB_NaN = 0x7fffffff;
private const int ILogB_Zero = (-1 - 0x7fffffff);
[Intrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float Abs(float x)
{
return Math.Abs(x);
}
public static float BitDecrement(float x)
{
int bits = BitConverter.SingleToInt32Bits(x);
if ((bits & 0x7F800000) >= 0x7F800000)
{
// NaN returns NaN
// -Infinity returns -Infinity
// +Infinity returns float.MaxValue
return (bits == 0x7F800000) ? float.MaxValue : x;
}
if (bits == 0x00000000)
{
// +0.0 returns -float.Epsilon
return -float.Epsilon;
}
// Negative values need to be incremented
// Positive values need to be decremented
bits += ((bits < 0) ? +1 : -1);
return BitConverter.Int32BitsToSingle(bits);
}
public static float BitIncrement(float x)
{
int bits = BitConverter.SingleToInt32Bits(x);
if ((bits & 0x7F800000) >= 0x7F800000)
{
// NaN returns NaN
// -Infinity returns float.MinValue
// +Infinity returns +Infinity
return (bits == unchecked((int)(0xFF800000))) ? float.MinValue : x;
}
if (bits == unchecked((int)(0x80000000)))
{
// -0.0 returns float.Epsilon
return float.Epsilon;
}
// Negative values need to be decremented
// Positive values need to be incremented
bits += ((bits < 0) ? -1 : +1);
return BitConverter.Int32BitsToSingle(bits);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float CopySign(float x, float y)
{
if (Sse.IsSupported || AdvSimd.IsSupported)
{
return VectorMath.ConditionalSelectBitwise(Vector128.CreateScalarUnsafe(-0.0f), Vector128.CreateScalarUnsafe(y), Vector128.CreateScalarUnsafe(x)).ToScalar();
}
else
{
return SoftwareFallback(x, y);
}
static float SoftwareFallback(float x, float y)
{
const int signMask = 1 << 31;
// This method is required to work for all inputs,
// including NaN, so we operate on the raw bits.
int xbits = BitConverter.SingleToInt32Bits(x);
int ybits = BitConverter.SingleToInt32Bits(y);
// Remove the sign from x, and remove everything but the sign from y
xbits &= ~signMask;
ybits &= signMask;
// Simply OR them to get the correct sign
return BitConverter.Int32BitsToSingle(xbits | ybits);
}
}
public static float IEEERemainder(float x, float y)
{
if (float.IsNaN(x))
{
return x; // IEEE 754-2008: NaN payload must be preserved
}
if (float.IsNaN(y))
{
return y; // IEEE 754-2008: NaN payload must be preserved
}
float regularMod = x % y;
if (float.IsNaN(regularMod))
{
return float.NaN;
}
if ((regularMod == 0) && float.IsNegative(x))
{
return float.NegativeZero;
}
float alternativeResult = (regularMod - (Abs(y) * Sign(x)));
if (Abs(alternativeResult) == Abs(regularMod))
{
float divisionResult = x / y;
float roundedResult = Round(divisionResult);
if (Abs(roundedResult) > Abs(divisionResult))
{
return alternativeResult;
}
else
{
return regularMod;
}
}
if (Abs(alternativeResult) < Abs(regularMod))
{
return alternativeResult;
}
else
{
return regularMod;
}
}
public static int ILogB(float x)
{
// Implementation based on https://git.musl-libc.org/cgit/musl/tree/src/math/ilogbf.c
if (float.IsNaN(x))
{
return ILogB_NaN;
}
uint i = BitConverter.SingleToUInt32Bits(x);
int e = (int)((i >> 23) & 0xFF);
if (e == 0)
{
i <<= 9;
if (i == 0)
{
return ILogB_Zero;
}
for (e = -0x7F; (i >> 31) == 0; e--, i <<= 1) ;
return e;
}
if (e == 0xFF)
{
return i << 9 != 0 ? ILogB_Zero : int.MaxValue;
}
return e - 0x7F;
}
public static float Log(float x, float y)
{
if (float.IsNaN(x))
{
return x; // IEEE 754-2008: NaN payload must be preserved
}
if (float.IsNaN(y))
{
return y; // IEEE 754-2008: NaN payload must be preserved
}
if (y == 1)
{
return float.NaN;
}
if ((x != 1) && ((y == 0) || float.IsPositiveInfinity(y)))
{
return float.NaN;
}
return Log(x) / Log(y);
}
[Intrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float Max(float x, float y)
{
return Math.Max(x, y);
}
[Intrinsic]
public static float MaxMagnitude(float x, float y)
{
// This matches the IEEE 754:2019 `maximumMagnitude` function
//
// It propagates NaN inputs back to the caller and
// otherwise returns the input with a greater magnitude.
// It treats +0 as greater than -0 as per the specification.
float ax = Abs(x);
float ay = Abs(y);
if ((ax > ay) || float.IsNaN(ax))
{
return x;
}
if (ax == ay)
{
return float.IsNegative(x) ? y : x;
}
return y;
}
[Intrinsic]
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float Min(float x, float y)
{
return Math.Min(x, y);
}
[Intrinsic]
public static float MinMagnitude(float x, float y)
{
// This matches the IEEE 754:2019 `minimumMagnitude` function
//
// It propagates NaN inputs back to the caller and
// otherwise returns the input with a lesser magnitude.
// It treats +0 as greater than -0 as per the specification.
float ax = Abs(x);
float ay = Abs(y);
if ((ax < ay) || float.IsNaN(ax))
{
return x;
}
if (ax == ay)
{
return float.IsNegative(x) ? x : y;
}
return y;
}
/// <summary>Returns an estimate of the reciprocal of a specified number.</summary>
/// <param name="x">The number whose reciprocal is to be estimated.</param>
/// <returns>An estimate of the reciprocal of <paramref name="x" />.</returns>
/// <remarks>
/// <para>On x86/x64 hardware this may use the <c>RCPSS</c> instruction which has a maximum relative error of <c>1.5 * 2^-12</c>.</para>
/// <para>On ARM64 hardware this may use the <c>FRECPE</c> instruction which performs a single Newton-Raphson iteration.</para>
/// <para>On hardware without specialized support, this may just return <c>1.0 / x</c>.</para>
/// </remarks>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float ReciprocalEstimate(float x)
{
if (Sse.IsSupported)
{
return Sse.ReciprocalScalar(Vector128.CreateScalarUnsafe(x)).ToScalar();
}
else if (AdvSimd.Arm64.IsSupported)
{
return AdvSimd.Arm64.ReciprocalEstimateScalar(Vector64.CreateScalarUnsafe(x)).ToScalar();
}
else
{
return 1.0f / x;
}
}
/// <summary>Returns an estimate of the reciprocal square root of a specified number.</summary>
/// <param name="x">The number whose reciprocal square root is to be estimated.</param>
/// <returns>An estimate of the reciprocal square root <paramref name="x" />.</returns>
/// <remarks>
/// <para>On x86/x64 hardware this may use the <c>RSQRTSS</c> instruction which has a maximum relative error of <c>1.5 * 2^-12</c>.</para>
/// <para>On ARM64 hardware this may use the <c>FRSQRTE</c> instruction which performs a single Newton-Raphson iteration.</para>
/// <para>On hardware without specialized support, this may just return <c>1.0 / Sqrt(x)</c>.</para>
/// </remarks>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float ReciprocalSqrtEstimate(float x)
{
if (Sse.IsSupported)
{
return Sse.ReciprocalSqrtScalar(Vector128.CreateScalarUnsafe(x)).ToScalar();
}
else if (AdvSimd.Arm64.IsSupported)
{
return AdvSimd.Arm64.ReciprocalSquareRootEstimateScalar(Vector64.CreateScalarUnsafe(x)).ToScalar();
}
else
{
return 1.0f / Sqrt(x);
}
}
[Intrinsic]
public static float Round(float x)
{
// ************************************************************************************
// IMPORTANT: Do not change this implementation without also updating MathF.Round(float),
// FloatingPointUtils::round(double), and FloatingPointUtils::round(float)
// ************************************************************************************
// This is based on the 'Berkeley SoftFloat Release 3e' algorithm
uint bits = BitConverter.SingleToUInt32Bits(x);
byte biasedExponent = float.ExtractBiasedExponentFromBits(bits);
if (biasedExponent <= 0x7E)
{
if ((bits << 1) == 0)
{
// Exactly +/- zero should return the original value
return x;
}
// Any value less than or equal to 0.5 will always round to exactly zero
// and any value greater than 0.5 will always round to exactly one. However,
// we need to preserve the original sign for IEEE compliance.
float result = ((biasedExponent == 0x7E) && (float.ExtractTrailingSignificandFromBits(bits) != 0)) ? 1.0f : 0.0f;
return CopySign(result, x);
}
if (biasedExponent >= 0x96)
{
// Any value greater than or equal to 2^23 cannot have a fractional part,
// So it will always round to exactly itself.
return x;
}
// The absolute value should be greater than or equal to 1.0 and less than 2^23
Debug.Assert((0x7F <= biasedExponent) && (biasedExponent <= 0x95));
// Determine the last bit that represents the integral portion of the value
// and the bits representing the fractional portion
uint lastBitMask = 1U << (0x96 - biasedExponent);
uint roundBitsMask = lastBitMask - 1;
// Increment the first fractional bit, which represents the midpoint between
// two integral values in the current window.
bits += lastBitMask >> 1;
if ((bits & roundBitsMask) == 0)
{
// If that overflowed and the rest of the fractional bits are zero
// then we were exactly x.5 and we want to round to the even result
bits &= ~lastBitMask;
}
else
{
// Otherwise, we just want to strip the fractional bits off, truncating
// to the current integer value.
bits &= ~roundBitsMask;
}
return BitConverter.UInt32BitsToSingle(bits);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float Round(float x, int digits)
{
return Round(x, digits, MidpointRounding.ToEven);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static float Round(float x, MidpointRounding mode)
{
// Inline single-instruction modes
if (RuntimeHelpers.IsKnownConstant((int)mode))
{
if (mode == MidpointRounding.ToEven)
return Round(x);
// For ARM/ARM64 we can lower it down to a single instruction FRINTA
// For other platforms we use a fast managed implementation
if (mode == MidpointRounding.AwayFromZero)
{
if (AdvSimd.IsSupported)
return AdvSimd.RoundAwayFromZeroScalar(Vector64.CreateScalarUnsafe(x)).ToScalar();
// manually fold BitDecrement(0.5f)
return Truncate(x + CopySign(0.49999997f, x));
}
}
return Round(x, 0, mode);
}
public static unsafe float Round(float x, int digits, MidpointRounding mode)
{
if ((digits < 0) || (digits > maxRoundingDigits))
{
throw new ArgumentOutOfRangeException(nameof(digits), SR.ArgumentOutOfRange_RoundingDigits_MathF);
}
if (mode < MidpointRounding.ToEven || mode > MidpointRounding.ToPositiveInfinity)
{
throw new ArgumentException(SR.Format(SR.Argument_InvalidEnumValue, mode, nameof(MidpointRounding)), nameof(mode));
}
if (Abs(x) < singleRoundLimit)
{
float power10 = RoundPower10Single[digits];
x *= power10;
switch (mode)
{
// Rounds to the nearest value; if the number falls midway,
// it is rounded to the nearest value with an even least significant digit
case MidpointRounding.ToEven:
{
x = Round(x);
break;
}
// Rounds to the nearest value; if the number falls midway,
// it is rounded to the nearest value above (for positive numbers) or below (for negative numbers)
case MidpointRounding.AwayFromZero:
{
// manually fold BitDecrement(0.5f)
x = Truncate(x + CopySign(0.49999997f, x));
break;
}
// Directed rounding: Round to the nearest value, toward to zero
case MidpointRounding.ToZero:
{
x = Truncate(x);
break;
}
// Directed Rounding: Round down to the next value, toward negative infinity
case MidpointRounding.ToNegativeInfinity:
{
x = Floor(x);
break;
}
// Directed rounding: Round up to the next value, toward positive infinity
case MidpointRounding.ToPositiveInfinity:
{
x = Ceiling(x);
break;
}
default:
{
throw new ArgumentException(SR.Format(SR.Argument_InvalidEnumValue, mode, nameof(MidpointRounding)), nameof(mode));
}
}
x /= power10;
}
return x;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int Sign(float x)
{
return Math.Sign(x);
}
[Intrinsic]
public static unsafe float Truncate(float x)
{
ModF(x, &x);
return x;
}
public static float ScaleB(float x, int n)
{
// Implementation based on https://git.musl-libc.org/cgit/musl/tree/src/math/scalblnf.c
//
// Performs the calculation x * 2^n efficiently. It constructs a float from 2^n by building
// the correct biased exponent. If n is greater than the maximum exponent (127) or less than
// the minimum exponent (-126), adjust x and n to compute correct result.
float y = x;
if (n > 127)
{
y *= SCALEB_C1;
n -= 127;
if (n > 127)
{
y *= SCALEB_C1;
n -= 127;
if (n > 127)
{
n = 127;
}
}
}
else if (n < -126)
{
y *= SCALEB_C2 * SCALEB_C3;
n += 126 - 24;
if (n < -126)
{
y *= SCALEB_C2 * SCALEB_C3;
n += 126 - 24;
if (n < -126)
{
n = -126;
}
}
}
float u = BitConverter.Int32BitsToSingle(((int)(0x7f + n) << 23));
return y * u;
}
}
}