MathF.cs 11 KB

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