MathF.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  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. ** Purpose: Some single-precision floating-point math operations
  10. **
  11. ===========================================================*/
  12. using System.Diagnostics;
  13. using System.Runtime.CompilerServices;
  14. namespace System
  15. {
  16. public static partial class MathF
  17. {
  18. public const float E = 2.71828183f;
  19. public const float PI = 3.14159265f;
  20. private const int maxRoundingDigits = 6;
  21. // This table is required for the Round function which can specify the number of digits to round to
  22. private static readonly float[] roundPower10Single = new float[] {
  23. 1e0f, 1e1f, 1e2f, 1e3f, 1e4f, 1e5f, 1e6f
  24. };
  25. private const float singleRoundLimit = 1e8f;
  26. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  27. public static float Abs(float x)
  28. {
  29. return Math.Abs(x);
  30. }
  31. public static float BitDecrement(float x)
  32. {
  33. int bits = BitConverter.SingleToInt32Bits(x);
  34. if ((bits & 0x7F800000) >= 0x7F800000)
  35. {
  36. // NaN returns NaN
  37. // -Infinity returns -Infinity
  38. // +Infinity returns float.MaxValue
  39. return (bits == 0x7F800000) ? float.MaxValue : x;
  40. }
  41. if (bits == 0x00000000)
  42. {
  43. // +0.0 returns -float.Epsilon
  44. return -float.Epsilon;
  45. }
  46. // Negative values need to be incremented
  47. // Positive values need to be decremented
  48. bits += ((bits < 0) ? +1 : -1);
  49. return BitConverter.Int32BitsToSingle(bits);
  50. }
  51. public static float BitIncrement(float x)
  52. {
  53. int bits = BitConverter.SingleToInt32Bits(x);
  54. if ((bits & 0x7F800000) >= 0x7F800000)
  55. {
  56. // NaN returns NaN
  57. // -Infinity returns float.MinValue
  58. // +Infinity returns +Infinity
  59. return (bits == unchecked((int)(0xFF800000))) ? float.MinValue : x;
  60. }
  61. if (bits == unchecked((int)(0x80000000)))
  62. {
  63. // -0.0 returns float.Epsilon
  64. return float.Epsilon;
  65. }
  66. // Negative values need to be decremented
  67. // Positive values need to be incremented
  68. bits += ((bits < 0) ? -1 : +1);
  69. return BitConverter.Int32BitsToSingle(bits);
  70. }
  71. public static unsafe float CopySign(float x, float y)
  72. {
  73. // This method is required to work for all inputs,
  74. // including NaN, so we operate on the raw bits.
  75. int xbits = BitConverter.SingleToInt32Bits(x);
  76. int ybits = BitConverter.SingleToInt32Bits(y);
  77. // If the sign bits of x and y are not the same,
  78. // flip the sign bit of x and return the new value;
  79. // otherwise, just return x
  80. if ((xbits ^ ybits) < 0)
  81. {
  82. return BitConverter.Int32BitsToSingle(xbits ^ int.MinValue);
  83. }
  84. return x;
  85. }
  86. public static float IEEERemainder(float x, float y)
  87. {
  88. if (float.IsNaN(x))
  89. {
  90. return x; // IEEE 754-2008: NaN payload must be preserved
  91. }
  92. if (float.IsNaN(y))
  93. {
  94. return y; // IEEE 754-2008: NaN payload must be preserved
  95. }
  96. float regularMod = x % y;
  97. if (float.IsNaN(regularMod))
  98. {
  99. return float.NaN;
  100. }
  101. if ((regularMod == 0) && float.IsNegative(x))
  102. {
  103. return float.NegativeZero;
  104. }
  105. float alternativeResult = (regularMod - (Abs(y) * Sign(x)));
  106. if (Abs(alternativeResult) == Abs(regularMod))
  107. {
  108. float divisionResult = x / y;
  109. float roundedResult = Round(divisionResult);
  110. if (Abs(roundedResult) > Abs(divisionResult))
  111. {
  112. return alternativeResult;
  113. }
  114. else
  115. {
  116. return regularMod;
  117. }
  118. }
  119. if (Abs(alternativeResult) < Abs(regularMod))
  120. {
  121. return alternativeResult;
  122. }
  123. else
  124. {
  125. return regularMod;
  126. }
  127. }
  128. public static float Log(float x, float y)
  129. {
  130. if (float.IsNaN(x))
  131. {
  132. return x; // IEEE 754-2008: NaN payload must be preserved
  133. }
  134. if (float.IsNaN(y))
  135. {
  136. return y; // IEEE 754-2008: NaN payload must be preserved
  137. }
  138. if (y == 1)
  139. {
  140. return float.NaN;
  141. }
  142. if ((x != 1) && ((y == 0) || float.IsPositiveInfinity(y)))
  143. {
  144. return float.NaN;
  145. }
  146. return Log(x) / Log(y);
  147. }
  148. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  149. public static float Max(float x, float y)
  150. {
  151. return Math.Max(x, y);
  152. }
  153. public static float MaxMagnitude(float x, float y)
  154. {
  155. // This matches the IEEE 754:2019 `maximumMagnitude` function
  156. //
  157. // It propagates NaN inputs back to the caller and
  158. // otherwise returns the input with a larger magnitude.
  159. // It treats +0 as larger than -0 as per the specification.
  160. float ax = Abs(x);
  161. float ay = Abs(y);
  162. if ((ax > ay) || float.IsNaN(ax))
  163. {
  164. return x;
  165. }
  166. if (ax == ay)
  167. {
  168. return float.IsNegative(x) ? y : x;
  169. }
  170. return y;
  171. }
  172. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  173. public static float Min(float x, float y)
  174. {
  175. return Math.Min(x, y);
  176. }
  177. public static float MinMagnitude(float x, float y)
  178. {
  179. // This matches the IEEE 754:2019 `minimumMagnitude` function
  180. //
  181. // It propagates NaN inputs back to the caller and
  182. // otherwise returns the input with a larger magnitude.
  183. // It treats +0 as larger than -0 as per the specification.
  184. float ax = Abs(x);
  185. float ay = Abs(y);
  186. if ((ax < ay) || float.IsNaN(ax))
  187. {
  188. return x;
  189. }
  190. if (ax == ay)
  191. {
  192. return float.IsNegative(x) ? x : y;
  193. }
  194. return y;
  195. }
  196. [Intrinsic]
  197. public static float Round(float x)
  198. {
  199. // ************************************************************************************
  200. // IMPORTANT: Do not change this implementation without also updating MathF.Round(float),
  201. // FloatingPointUtils::round(double), and FloatingPointUtils::round(float)
  202. // ************************************************************************************
  203. // This is based on the 'Berkeley SoftFloat Release 3e' algorithm
  204. uint bits = (uint)BitConverter.SingleToInt32Bits(x);
  205. int exponent = float.ExtractExponentFromBits(bits);
  206. if (exponent <= 0x7E)
  207. {
  208. if ((bits << 1) == 0)
  209. {
  210. // Exactly +/- zero should return the original value
  211. return x;
  212. }
  213. // Any value less than or equal to 0.5 will always round to exactly zero
  214. // and any value greater than 0.5 will always round to exactly one. However,
  215. // we need to preserve the original sign for IEEE compliance.
  216. float result = ((exponent == 0x7E) && (float.ExtractSignificandFromBits(bits) != 0)) ? 1.0f : 0.0f;
  217. return CopySign(result, x);
  218. }
  219. if (exponent >= 0x96)
  220. {
  221. // Any value greater than or equal to 2^23 cannot have a fractional part,
  222. // So it will always round to exactly itself.
  223. return x;
  224. }
  225. // The absolute value should be greater than or equal to 1.0 and less than 2^23
  226. Debug.Assert((0x7F <= exponent) && (exponent <= 0x95));
  227. // Determine the last bit that represents the integral portion of the value
  228. // and the bits representing the fractional portion
  229. uint lastBitMask = 1U << (0x96 - exponent);
  230. uint roundBitsMask = lastBitMask - 1;
  231. // Increment the first fractional bit, which represents the midpoint between
  232. // two integral values in the current window.
  233. bits += lastBitMask >> 1;
  234. if ((bits & roundBitsMask) == 0)
  235. {
  236. // If that overflowed and the rest of the fractional bits are zero
  237. // then we were exactly x.5 and we want to round to the even result
  238. bits &= ~lastBitMask;
  239. }
  240. else
  241. {
  242. // Otherwise, we just want to strip the fractional bits off, truncating
  243. // to the current integer value.
  244. bits &= ~roundBitsMask;
  245. }
  246. return BitConverter.Int32BitsToSingle((int)bits);
  247. }
  248. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  249. public static float Round(float x, int digits)
  250. {
  251. return Round(x, digits, MidpointRounding.ToEven);
  252. }
  253. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  254. public static float Round(float x, MidpointRounding mode)
  255. {
  256. return Round(x, 0, mode);
  257. }
  258. public static unsafe float Round(float x, int digits, MidpointRounding mode)
  259. {
  260. if ((digits < 0) || (digits > maxRoundingDigits))
  261. {
  262. throw new ArgumentOutOfRangeException(nameof(digits), SR.ArgumentOutOfRange_RoundingDigits);
  263. }
  264. if (mode < MidpointRounding.ToEven || mode > MidpointRounding.ToPositiveInfinity)
  265. {
  266. throw new ArgumentException(SR.Format(SR.Argument_InvalidEnumValue, mode, nameof(MidpointRounding)), nameof(mode));
  267. }
  268. if (Abs(x) < singleRoundLimit)
  269. {
  270. float power10 = roundPower10Single[digits];
  271. x *= power10;
  272. switch (mode)
  273. {
  274. // Rounds to the nearest value; if the number falls midway,
  275. // it is rounded to the nearest value with an even least significant digit
  276. case MidpointRounding.ToEven:
  277. {
  278. x = Round(x);
  279. break;
  280. }
  281. // Rounds to the nearest value; if the number falls midway,
  282. // it is rounded to the nearest value above (for positive numbers) or below (for negative numbers)
  283. case MidpointRounding.AwayFromZero:
  284. {
  285. float fraction = ModF(x, &x);
  286. if (Abs(fraction) >= 0.5)
  287. {
  288. x += Sign(fraction);
  289. }
  290. break;
  291. }
  292. // Directed rounding: Round to the nearest value, toward to zero
  293. case MidpointRounding.ToZero:
  294. {
  295. x = Truncate(x);
  296. break;
  297. }
  298. // Directed Rounding: Round down to the next value, toward negative infinity
  299. case MidpointRounding.ToNegativeInfinity:
  300. {
  301. x = Floor(x);
  302. break;
  303. }
  304. // Directed rounding: Round up to the next value, toward positive infinity
  305. case MidpointRounding.ToPositiveInfinity:
  306. {
  307. x = Ceiling(x);
  308. break;
  309. }
  310. default:
  311. {
  312. throw new ArgumentException(SR.Format(SR.Argument_InvalidEnumValue, mode, nameof(MidpointRounding)), nameof(mode));
  313. }
  314. }
  315. x /= power10;
  316. }
  317. return x;
  318. }
  319. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  320. public static int Sign(float x)
  321. {
  322. return Math.Sign(x);
  323. }
  324. public static unsafe float Truncate(float x)
  325. {
  326. ModF(x, &x);
  327. return x;
  328. }
  329. }
  330. }