Math.cs 29 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036
  1. // Licensed to the .NET Foundation under one or more agreements.
  2. // The .NET Foundation licenses this file to you under the MIT license.
  3. // See the LICENSE file in the project root for more information.
  4. // ===================================================================================================
  5. // Portions of the code implemented below are based on the 'Berkeley SoftFloat Release 3e' algorithms.
  6. // ===================================================================================================
  7. /*============================================================
  8. **
  9. **
  10. **
  11. ** Purpose: Some floating-point math operations
  12. **
  13. **
  14. ===========================================================*/
  15. using System.Diagnostics;
  16. using System.Diagnostics.CodeAnalysis;
  17. using System.Runtime.CompilerServices;
  18. using System.Runtime.Versioning;
  19. namespace System
  20. {
  21. public static partial class Math
  22. {
  23. public const double E = 2.7182818284590452354;
  24. public const double PI = 3.14159265358979323846;
  25. private const int maxRoundingDigits = 15;
  26. private const double doubleRoundLimit = 1e16d;
  27. // This table is required for the Round function which can specify the number of digits to round to
  28. private static readonly double[] roundPower10Double = new double[] {
  29. 1E0, 1E1, 1E2, 1E3, 1E4, 1E5, 1E6, 1E7, 1E8,
  30. 1E9, 1E10, 1E11, 1E12, 1E13, 1E14, 1E15
  31. };
  32. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  33. public static short Abs(short value)
  34. {
  35. if (value < 0)
  36. {
  37. value = (short)-value;
  38. if (value < 0)
  39. {
  40. ThrowAbsOverflow();
  41. }
  42. }
  43. return value;
  44. }
  45. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  46. public static int Abs(int value)
  47. {
  48. if (value < 0)
  49. {
  50. value = -value;
  51. if (value < 0)
  52. {
  53. ThrowAbsOverflow();
  54. }
  55. }
  56. return value;
  57. }
  58. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  59. public static long Abs(long value)
  60. {
  61. if (value < 0)
  62. {
  63. value = -value;
  64. if (value < 0)
  65. {
  66. ThrowAbsOverflow();
  67. }
  68. }
  69. return value;
  70. }
  71. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  72. [CLSCompliant(false)]
  73. public static sbyte Abs(sbyte value)
  74. {
  75. if (value < 0)
  76. {
  77. value = (sbyte)-value;
  78. if (value < 0)
  79. {
  80. ThrowAbsOverflow();
  81. }
  82. }
  83. return value;
  84. }
  85. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  86. public static decimal Abs(decimal value)
  87. {
  88. return decimal.Abs(value);
  89. }
  90. [DoesNotReturn]
  91. [StackTraceHidden]
  92. private static void ThrowAbsOverflow()
  93. {
  94. throw new OverflowException(SR.Overflow_NegateTwosCompNum);
  95. }
  96. public static long BigMul(int a, int b)
  97. {
  98. return ((long)a) * b;
  99. }
  100. public static double BitDecrement(double x)
  101. {
  102. long bits = BitConverter.DoubleToInt64Bits(x);
  103. if (((bits >> 32) & 0x7FF00000) >= 0x7FF00000)
  104. {
  105. // NaN returns NaN
  106. // -Infinity returns -Infinity
  107. // +Infinity returns double.MaxValue
  108. return (bits == 0x7FF00000_00000000) ? double.MaxValue : x;
  109. }
  110. if (bits == 0x00000000_00000000)
  111. {
  112. // +0.0 returns -double.Epsilon
  113. return -double.Epsilon;
  114. }
  115. // Negative values need to be incremented
  116. // Positive values need to be decremented
  117. bits += ((bits < 0) ? +1 : -1);
  118. return BitConverter.Int64BitsToDouble(bits);
  119. }
  120. public static double BitIncrement(double x)
  121. {
  122. long bits = BitConverter.DoubleToInt64Bits(x);
  123. if (((bits >> 32) & 0x7FF00000) >= 0x7FF00000)
  124. {
  125. // NaN returns NaN
  126. // -Infinity returns double.MinValue
  127. // +Infinity returns +Infinity
  128. return (bits == unchecked((long)(0xFFF00000_00000000))) ? double.MinValue : x;
  129. }
  130. if (bits == unchecked((long)(0x80000000_00000000)))
  131. {
  132. // -0.0 returns double.Epsilon
  133. return double.Epsilon;
  134. }
  135. // Negative values need to be decremented
  136. // Positive values need to be incremented
  137. bits += ((bits < 0) ? -1 : +1);
  138. return BitConverter.Int64BitsToDouble(bits);
  139. }
  140. public static unsafe double CopySign(double x, double y)
  141. {
  142. // This method is required to work for all inputs,
  143. // including NaN, so we operate on the raw bits.
  144. long xbits = BitConverter.DoubleToInt64Bits(x);
  145. long ybits = BitConverter.DoubleToInt64Bits(y);
  146. // If the sign bits of x and y are not the same,
  147. // flip the sign bit of x and return the new value;
  148. // otherwise, just return x
  149. if ((xbits ^ ybits) < 0)
  150. {
  151. return BitConverter.Int64BitsToDouble(xbits ^ long.MinValue);
  152. }
  153. return x;
  154. }
  155. public static int DivRem(int a, int b, out int result)
  156. {
  157. // TODO https://github.com/dotnet/coreclr/issues/3439:
  158. // Restore to using % and / when the JIT is able to eliminate one of the idivs.
  159. // In the meantime, a * and - is measurably faster than an extra /.
  160. int div = a / b;
  161. result = a - (div * b);
  162. return div;
  163. }
  164. public static long DivRem(long a, long b, out long result)
  165. {
  166. long div = a / b;
  167. result = a - (div * b);
  168. return div;
  169. }
  170. internal static uint DivRem(uint a, uint b, out uint result)
  171. {
  172. uint div = a / b;
  173. result = a - (div * b);
  174. return div;
  175. }
  176. internal static ulong DivRem(ulong a, ulong b, out ulong result)
  177. {
  178. ulong div = a / b;
  179. result = a - (div * b);
  180. return div;
  181. }
  182. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  183. public static decimal Ceiling(decimal d)
  184. {
  185. return decimal.Ceiling(d);
  186. }
  187. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  188. public static byte Clamp(byte value, byte min, byte max)
  189. {
  190. if (min > max)
  191. {
  192. ThrowMinMaxException(min, max);
  193. }
  194. if (value < min)
  195. {
  196. return min;
  197. }
  198. else if (value > max)
  199. {
  200. return max;
  201. }
  202. return value;
  203. }
  204. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  205. public static decimal Clamp(decimal value, decimal min, decimal max)
  206. {
  207. if (min > max)
  208. {
  209. ThrowMinMaxException(min, max);
  210. }
  211. if (value < min)
  212. {
  213. return min;
  214. }
  215. else if (value > max)
  216. {
  217. return max;
  218. }
  219. return value;
  220. }
  221. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  222. public static double Clamp(double value, double min, double max)
  223. {
  224. if (min > max)
  225. {
  226. ThrowMinMaxException(min, max);
  227. }
  228. if (value < min)
  229. {
  230. return min;
  231. }
  232. else if (value > max)
  233. {
  234. return max;
  235. }
  236. return value;
  237. }
  238. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  239. public static short Clamp(short value, short min, short max)
  240. {
  241. if (min > max)
  242. {
  243. ThrowMinMaxException(min, max);
  244. }
  245. if (value < min)
  246. {
  247. return min;
  248. }
  249. else if (value > max)
  250. {
  251. return max;
  252. }
  253. return value;
  254. }
  255. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  256. public static int Clamp(int value, int min, int max)
  257. {
  258. if (min > max)
  259. {
  260. ThrowMinMaxException(min, max);
  261. }
  262. if (value < min)
  263. {
  264. return min;
  265. }
  266. else if (value > max)
  267. {
  268. return max;
  269. }
  270. return value;
  271. }
  272. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  273. public static long Clamp(long value, long min, long max)
  274. {
  275. if (min > max)
  276. {
  277. ThrowMinMaxException(min, max);
  278. }
  279. if (value < min)
  280. {
  281. return min;
  282. }
  283. else if (value > max)
  284. {
  285. return max;
  286. }
  287. return value;
  288. }
  289. [CLSCompliant(false)]
  290. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  291. public static sbyte Clamp(sbyte value, sbyte min, sbyte max)
  292. {
  293. if (min > max)
  294. {
  295. ThrowMinMaxException(min, max);
  296. }
  297. if (value < min)
  298. {
  299. return min;
  300. }
  301. else if (value > max)
  302. {
  303. return max;
  304. }
  305. return value;
  306. }
  307. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  308. public static float Clamp(float value, float min, float max)
  309. {
  310. if (min > max)
  311. {
  312. ThrowMinMaxException(min, max);
  313. }
  314. if (value < min)
  315. {
  316. return min;
  317. }
  318. else if (value > max)
  319. {
  320. return max;
  321. }
  322. return value;
  323. }
  324. [CLSCompliant(false)]
  325. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  326. public static ushort Clamp(ushort value, ushort min, ushort max)
  327. {
  328. if (min > max)
  329. {
  330. ThrowMinMaxException(min, max);
  331. }
  332. if (value < min)
  333. {
  334. return min;
  335. }
  336. else if (value > max)
  337. {
  338. return max;
  339. }
  340. return value;
  341. }
  342. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  343. [CLSCompliant(false)]
  344. public static uint Clamp(uint value, uint min, uint max)
  345. {
  346. if (min > max)
  347. {
  348. ThrowMinMaxException(min, max);
  349. }
  350. if (value < min)
  351. {
  352. return min;
  353. }
  354. else if (value > max)
  355. {
  356. return max;
  357. }
  358. return value;
  359. }
  360. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  361. [CLSCompliant(false)]
  362. public static ulong Clamp(ulong value, ulong min, ulong max)
  363. {
  364. if (min > max)
  365. {
  366. ThrowMinMaxException(min, max);
  367. }
  368. if (value < min)
  369. {
  370. return min;
  371. }
  372. else if (value > max)
  373. {
  374. return max;
  375. }
  376. return value;
  377. }
  378. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  379. public static decimal Floor(decimal d)
  380. {
  381. return decimal.Floor(d);
  382. }
  383. public static double IEEERemainder(double x, double y)
  384. {
  385. if (double.IsNaN(x))
  386. {
  387. return x; // IEEE 754-2008: NaN payload must be preserved
  388. }
  389. if (double.IsNaN(y))
  390. {
  391. return y; // IEEE 754-2008: NaN payload must be preserved
  392. }
  393. double regularMod = x % y;
  394. if (double.IsNaN(regularMod))
  395. {
  396. return double.NaN;
  397. }
  398. if ((regularMod == 0) && double.IsNegative(x))
  399. {
  400. return double.NegativeZero;
  401. }
  402. double alternativeResult = (regularMod - (Abs(y) * Sign(x)));
  403. if (Abs(alternativeResult) == Abs(regularMod))
  404. {
  405. double divisionResult = x / y;
  406. double roundedResult = Round(divisionResult);
  407. if (Abs(roundedResult) > Abs(divisionResult))
  408. {
  409. return alternativeResult;
  410. }
  411. else
  412. {
  413. return regularMod;
  414. }
  415. }
  416. if (Abs(alternativeResult) < Abs(regularMod))
  417. {
  418. return alternativeResult;
  419. }
  420. else
  421. {
  422. return regularMod;
  423. }
  424. }
  425. public static double Log(double a, double newBase)
  426. {
  427. if (double.IsNaN(a))
  428. {
  429. return a; // IEEE 754-2008: NaN payload must be preserved
  430. }
  431. if (double.IsNaN(newBase))
  432. {
  433. return newBase; // IEEE 754-2008: NaN payload must be preserved
  434. }
  435. if (newBase == 1)
  436. {
  437. return double.NaN;
  438. }
  439. if ((a != 1) && ((newBase == 0) || double.IsPositiveInfinity(newBase)))
  440. {
  441. return double.NaN;
  442. }
  443. return Log(a) / Log(newBase);
  444. }
  445. [NonVersionable]
  446. public static byte Max(byte val1, byte val2)
  447. {
  448. return (val1 >= val2) ? val1 : val2;
  449. }
  450. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  451. public static decimal Max(decimal val1, decimal val2)
  452. {
  453. return decimal.Max(val1, val2);
  454. }
  455. public static double Max(double val1, double val2)
  456. {
  457. // This matches the IEEE 754:2019 `maximum` function
  458. //
  459. // It propagates NaN inputs back to the caller and
  460. // otherwise returns the larger of the inputs. It
  461. // treats +0 as larger than -0 as per the specification.
  462. if ((val1 > val2) || double.IsNaN(val1))
  463. {
  464. return val1;
  465. }
  466. if (val1 == val2)
  467. {
  468. return double.IsNegative(val1) ? val2 : val1;
  469. }
  470. return val2;
  471. }
  472. [NonVersionable]
  473. public static short Max(short val1, short val2)
  474. {
  475. return (val1 >= val2) ? val1 : val2;
  476. }
  477. [NonVersionable]
  478. public static int Max(int val1, int val2)
  479. {
  480. return (val1 >= val2) ? val1 : val2;
  481. }
  482. [NonVersionable]
  483. public static long Max(long val1, long val2)
  484. {
  485. return (val1 >= val2) ? val1 : val2;
  486. }
  487. [CLSCompliant(false)]
  488. [NonVersionable]
  489. public static sbyte Max(sbyte val1, sbyte val2)
  490. {
  491. return (val1 >= val2) ? val1 : val2;
  492. }
  493. public static float Max(float val1, float val2)
  494. {
  495. // This matches the IEEE 754:2019 `maximum` function
  496. //
  497. // It propagates NaN inputs back to the caller and
  498. // otherwise returns the larger of the inputs. It
  499. // treats +0 as larger than -0 as per the specification.
  500. if ((val1 > val2) || float.IsNaN(val1))
  501. {
  502. return val1;
  503. }
  504. if (val1 == val2)
  505. {
  506. return float.IsNegative(val1) ? val2 : val1;
  507. }
  508. return val2;
  509. }
  510. [CLSCompliant(false)]
  511. [NonVersionable]
  512. public static ushort Max(ushort val1, ushort val2)
  513. {
  514. return (val1 >= val2) ? val1 : val2;
  515. }
  516. [CLSCompliant(false)]
  517. [NonVersionable]
  518. public static uint Max(uint val1, uint val2)
  519. {
  520. return (val1 >= val2) ? val1 : val2;
  521. }
  522. [CLSCompliant(false)]
  523. [NonVersionable]
  524. public static ulong Max(ulong val1, ulong val2)
  525. {
  526. return (val1 >= val2) ? val1 : val2;
  527. }
  528. public static double MaxMagnitude(double x, double y)
  529. {
  530. // This matches the IEEE 754:2019 `maximumMagnitude` function
  531. //
  532. // It propagates NaN inputs back to the caller and
  533. // otherwise returns the input with a larger magnitude.
  534. // It treats +0 as larger than -0 as per the specification.
  535. double ax = Abs(x);
  536. double ay = Abs(y);
  537. if ((ax > ay) || double.IsNaN(ax))
  538. {
  539. return x;
  540. }
  541. if (ax == ay)
  542. {
  543. return double.IsNegative(x) ? y : x;
  544. }
  545. return y;
  546. }
  547. [NonVersionable]
  548. public static byte Min(byte val1, byte val2)
  549. {
  550. return (val1 <= val2) ? val1 : val2;
  551. }
  552. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  553. public static decimal Min(decimal val1, decimal val2)
  554. {
  555. return decimal.Min(val1, val2);
  556. }
  557. public static double Min(double val1, double val2)
  558. {
  559. // This matches the IEEE 754:2019 `minimum` function
  560. //
  561. // It propagates NaN inputs back to the caller and
  562. // otherwise returns the larger of the inputs. It
  563. // treats +0 as larger than -0 as per the specification.
  564. if ((val1 < val2) || double.IsNaN(val1))
  565. {
  566. return val1;
  567. }
  568. if (val1 == val2)
  569. {
  570. return double.IsNegative(val1) ? val1 : val2;
  571. }
  572. return val2;
  573. }
  574. [NonVersionable]
  575. public static short Min(short val1, short val2)
  576. {
  577. return (val1 <= val2) ? val1 : val2;
  578. }
  579. [NonVersionable]
  580. public static int Min(int val1, int val2)
  581. {
  582. return (val1 <= val2) ? val1 : val2;
  583. }
  584. [NonVersionable]
  585. public static long Min(long val1, long val2)
  586. {
  587. return (val1 <= val2) ? val1 : val2;
  588. }
  589. [CLSCompliant(false)]
  590. [NonVersionable]
  591. public static sbyte Min(sbyte val1, sbyte val2)
  592. {
  593. return (val1 <= val2) ? val1 : val2;
  594. }
  595. public static float Min(float val1, float val2)
  596. {
  597. // This matches the IEEE 754:2019 `minimum` function
  598. //
  599. // It propagates NaN inputs back to the caller and
  600. // otherwise returns the larger of the inputs. It
  601. // treats +0 as larger than -0 as per the specification.
  602. if ((val1 < val2) || float.IsNaN(val1))
  603. {
  604. return val1;
  605. }
  606. if (val1 == val2)
  607. {
  608. return float.IsNegative(val1) ? val1 : val2;
  609. }
  610. return val2;
  611. }
  612. [CLSCompliant(false)]
  613. [NonVersionable]
  614. public static ushort Min(ushort val1, ushort val2)
  615. {
  616. return (val1 <= val2) ? val1 : val2;
  617. }
  618. [CLSCompliant(false)]
  619. [NonVersionable]
  620. public static uint Min(uint val1, uint val2)
  621. {
  622. return (val1 <= val2) ? val1 : val2;
  623. }
  624. [CLSCompliant(false)]
  625. [NonVersionable]
  626. public static ulong Min(ulong val1, ulong val2)
  627. {
  628. return (val1 <= val2) ? val1 : val2;
  629. }
  630. public static double MinMagnitude(double x, double y)
  631. {
  632. // This matches the IEEE 754:2019 `minimumMagnitude` function
  633. //
  634. // It propagates NaN inputs back to the caller and
  635. // otherwise returns the input with a larger magnitude.
  636. // It treats +0 as larger than -0 as per the specification.
  637. double ax = Abs(x);
  638. double ay = Abs(y);
  639. if ((ax < ay) || double.IsNaN(ax))
  640. {
  641. return x;
  642. }
  643. if (ax == ay)
  644. {
  645. return double.IsNegative(x) ? x : y;
  646. }
  647. return y;
  648. }
  649. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  650. public static decimal Round(decimal d)
  651. {
  652. return decimal.Round(d, 0);
  653. }
  654. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  655. public static decimal Round(decimal d, int decimals)
  656. {
  657. return decimal.Round(d, decimals);
  658. }
  659. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  660. public static decimal Round(decimal d, MidpointRounding mode)
  661. {
  662. return decimal.Round(d, 0, mode);
  663. }
  664. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  665. public static decimal Round(decimal d, int decimals, MidpointRounding mode)
  666. {
  667. return decimal.Round(d, decimals, mode);
  668. }
  669. [Intrinsic]
  670. public static double Round(double a)
  671. {
  672. // ************************************************************************************
  673. // IMPORTANT: Do not change this implementation without also updating MathF.Round(float),
  674. // FloatingPointUtils::round(double), and FloatingPointUtils::round(float)
  675. // ************************************************************************************
  676. // This is based on the 'Berkeley SoftFloat Release 3e' algorithm
  677. ulong bits = (ulong)BitConverter.DoubleToInt64Bits(a);
  678. int exponent = double.ExtractExponentFromBits(bits);
  679. if (exponent <= 0x03FE)
  680. {
  681. if ((bits << 1) == 0)
  682. {
  683. // Exactly +/- zero should return the original value
  684. return a;
  685. }
  686. // Any value less than or equal to 0.5 will always round to exactly zero
  687. // and any value greater than 0.5 will always round to exactly one. However,
  688. // we need to preserve the original sign for IEEE compliance.
  689. double result = ((exponent == 0x03FE) && (double.ExtractSignificandFromBits(bits) != 0)) ? 1.0 : 0.0;
  690. return CopySign(result, a);
  691. }
  692. if (exponent >= 0x0433)
  693. {
  694. // Any value greater than or equal to 2^52 cannot have a fractional part,
  695. // So it will always round to exactly itself.
  696. return a;
  697. }
  698. // The absolute value should be greater than or equal to 1.0 and less than 2^52
  699. Debug.Assert((0x03FF <= exponent) && (exponent <= 0x0432));
  700. // Determine the last bit that represents the integral portion of the value
  701. // and the bits representing the fractional portion
  702. ulong lastBitMask = 1UL << (0x0433 - exponent);
  703. ulong roundBitsMask = lastBitMask - 1;
  704. // Increment the first fractional bit, which represents the midpoint between
  705. // two integral values in the current window.
  706. bits += lastBitMask >> 1;
  707. if ((bits & roundBitsMask) == 0)
  708. {
  709. // If that overflowed and the rest of the fractional bits are zero
  710. // then we were exactly x.5 and we want to round to the even result
  711. bits &= ~lastBitMask;
  712. }
  713. else
  714. {
  715. // Otherwise, we just want to strip the fractional bits off, truncating
  716. // to the current integer value.
  717. bits &= ~roundBitsMask;
  718. }
  719. return BitConverter.Int64BitsToDouble((long)bits);
  720. }
  721. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  722. public static double Round(double value, int digits)
  723. {
  724. return Round(value, digits, MidpointRounding.ToEven);
  725. }
  726. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  727. public static double Round(double value, MidpointRounding mode)
  728. {
  729. return Round(value, 0, mode);
  730. }
  731. public static unsafe double Round(double value, int digits, MidpointRounding mode)
  732. {
  733. if ((digits < 0) || (digits > maxRoundingDigits))
  734. {
  735. throw new ArgumentOutOfRangeException(nameof(digits), SR.ArgumentOutOfRange_RoundingDigits);
  736. }
  737. if (mode < MidpointRounding.ToEven || mode > MidpointRounding.ToPositiveInfinity)
  738. {
  739. throw new ArgumentException(SR.Format(SR.Argument_InvalidEnumValue, mode, nameof(MidpointRounding)), nameof(mode));
  740. }
  741. if (Abs(value) < doubleRoundLimit)
  742. {
  743. double power10 = roundPower10Double[digits];
  744. value *= power10;
  745. switch (mode)
  746. {
  747. // Rounds to the nearest value; if the number falls midway,
  748. // it is rounded to the nearest value with an even least significant digit
  749. case MidpointRounding.ToEven:
  750. {
  751. value = Round(value);
  752. break;
  753. }
  754. // Rounds to the nearest value; if the number falls midway,
  755. // it is rounded to the nearest value above (for positive numbers) or below (for negative numbers)
  756. case MidpointRounding.AwayFromZero:
  757. {
  758. double fraction = ModF(value, &value);
  759. if (Abs(fraction) >= 0.5)
  760. {
  761. value += Sign(fraction);
  762. }
  763. break;
  764. }
  765. // Directed rounding: Round to the nearest value, toward to zero
  766. case MidpointRounding.ToZero:
  767. {
  768. value = Truncate(value);
  769. break;
  770. }
  771. // Directed Rounding: Round down to the next value, toward negative infinity
  772. case MidpointRounding.ToNegativeInfinity:
  773. {
  774. value = Floor(value);
  775. break;
  776. }
  777. // Directed rounding: Round up to the next value, toward positive infinity
  778. case MidpointRounding.ToPositiveInfinity:
  779. {
  780. value = Ceiling(value);
  781. break;
  782. }
  783. default:
  784. {
  785. throw new ArgumentException(SR.Format(SR.Argument_InvalidEnumValue, mode, nameof(MidpointRounding)), nameof(mode));
  786. }
  787. }
  788. value /= power10;
  789. }
  790. return value;
  791. }
  792. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  793. public static int Sign(decimal value)
  794. {
  795. return decimal.Sign(value);
  796. }
  797. public static int Sign(double value)
  798. {
  799. if (value < 0)
  800. {
  801. return -1;
  802. }
  803. else if (value > 0)
  804. {
  805. return 1;
  806. }
  807. else if (value == 0)
  808. {
  809. return 0;
  810. }
  811. throw new ArithmeticException(SR.Arithmetic_NaN);
  812. }
  813. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  814. public static int Sign(short value)
  815. {
  816. return Sign((int)value);
  817. }
  818. public static int Sign(int value)
  819. {
  820. return unchecked(value >> 31 | (int)((uint)-value >> 31));
  821. }
  822. public static int Sign(long value)
  823. {
  824. return unchecked((int)(value >> 63 | (long)((ulong)-value >> 63)));
  825. }
  826. [CLSCompliant(false)]
  827. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  828. public static int Sign(sbyte value)
  829. {
  830. return Sign((int)value);
  831. }
  832. public static int Sign(float value)
  833. {
  834. if (value < 0)
  835. {
  836. return -1;
  837. }
  838. else if (value > 0)
  839. {
  840. return 1;
  841. }
  842. else if (value == 0)
  843. {
  844. return 0;
  845. }
  846. throw new ArithmeticException(SR.Arithmetic_NaN);
  847. }
  848. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  849. public static decimal Truncate(decimal d)
  850. {
  851. return decimal.Truncate(d);
  852. }
  853. public static unsafe double Truncate(double d)
  854. {
  855. ModF(d, &d);
  856. return d;
  857. }
  858. [DoesNotReturn]
  859. private static void ThrowMinMaxException<T>(T min, T max)
  860. {
  861. throw new ArgumentException(SR.Format(SR.Argument_MinMaxValue, min, max));
  862. }
  863. }
  864. }