Math.cs 29 KB

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