MathF.cs 12 KB

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