Single.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  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: A wrapper class for the primitive type float.
  9. **
  10. **
  11. ===========================================================*/
  12. using System.Globalization;
  13. using System.Runtime.CompilerServices;
  14. using System.Runtime.InteropServices;
  15. using System.Runtime.Versioning;
  16. using Internal.Runtime.CompilerServices;
  17. namespace System
  18. {
  19. [Serializable]
  20. [StructLayout(LayoutKind.Sequential)]
  21. [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")]
  22. public readonly struct Single : IComparable, IConvertible, IFormattable, IComparable<float>, IEquatable<float>, ISpanFormattable
  23. {
  24. private readonly float m_value; // Do not rename (binary serialization)
  25. //
  26. // Public constants
  27. //
  28. public const float MinValue = (float)-3.40282346638528859e+38;
  29. public const float Epsilon = (float)1.4e-45;
  30. public const float MaxValue = (float)3.40282346638528859e+38;
  31. public const float PositiveInfinity = (float)1.0 / (float)0.0;
  32. public const float NegativeInfinity = (float)-1.0 / (float)0.0;
  33. public const float NaN = (float)0.0 / (float)0.0;
  34. // We use this explicit definition to avoid the confusion between 0.0 and -0.0.
  35. internal const float NegativeZero = (float)-0.0;
  36. /// <summary>Determines whether the specified value is finite (zero, subnormal, or normal).</summary>
  37. [NonVersionable]
  38. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  39. public static bool IsFinite(float f)
  40. {
  41. var bits = BitConverter.SingleToInt32Bits(f);
  42. return (bits & 0x7FFFFFFF) < 0x7F800000;
  43. }
  44. /// <summary>Determines whether the specified value is infinite.</summary>
  45. [NonVersionable]
  46. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  47. public static unsafe bool IsInfinity(float f)
  48. {
  49. var bits = BitConverter.SingleToInt32Bits(f);
  50. return (bits & 0x7FFFFFFF) == 0x7F800000;
  51. }
  52. /// <summary>Determines whether the specified value is NaN.</summary>
  53. [NonVersionable]
  54. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  55. public static unsafe bool IsNaN(float f)
  56. {
  57. var bits = BitConverter.SingleToInt32Bits(f);
  58. return (bits & 0x7FFFFFFF) > 0x7F800000;
  59. }
  60. /// <summary>Determines whether the specified value is negative.</summary>
  61. [NonVersionable]
  62. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  63. public static unsafe bool IsNegative(float f)
  64. {
  65. return BitConverter.SingleToInt32Bits(f) < 0;
  66. }
  67. /// <summary>Determines whether the specified value is negative infinity.</summary>
  68. [NonVersionable]
  69. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  70. public static unsafe bool IsNegativeInfinity(float f)
  71. {
  72. return (f == float.NegativeInfinity);
  73. }
  74. /// <summary>Determines whether the specified value is normal.</summary>
  75. [NonVersionable]
  76. // This is probably not worth inlining, it has branches and should be rarely called
  77. public static unsafe bool IsNormal(float f)
  78. {
  79. var bits = BitConverter.SingleToInt32Bits(f);
  80. bits &= 0x7FFFFFFF;
  81. return (bits < 0x7F800000) && (bits != 0) && ((bits & 0x7F800000) != 0);
  82. }
  83. /// <summary>Determines whether the specified value is positive infinity.</summary>
  84. [NonVersionable]
  85. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  86. public static unsafe bool IsPositiveInfinity(float f)
  87. {
  88. return (f == float.PositiveInfinity);
  89. }
  90. /// <summary>Determines whether the specified value is subnormal.</summary>
  91. [NonVersionable]
  92. // This is probably not worth inlining, it has branches and should be rarely called
  93. public static unsafe bool IsSubnormal(float f)
  94. {
  95. var bits = BitConverter.SingleToInt32Bits(f);
  96. bits &= 0x7FFFFFFF;
  97. return (bits < 0x7F800000) && (bits != 0) && ((bits & 0x7F800000) == 0);
  98. }
  99. // Compares this object to another object, returning an integer that
  100. // indicates the relationship.
  101. // Returns a value less than zero if this object
  102. // null is considered to be less than any instance.
  103. // If object is not of type Single, this method throws an ArgumentException.
  104. //
  105. public int CompareTo(object value)
  106. {
  107. if (value == null)
  108. {
  109. return 1;
  110. }
  111. if (value is float)
  112. {
  113. float f = (float)value;
  114. if (m_value < f) return -1;
  115. if (m_value > f) return 1;
  116. if (m_value == f) return 0;
  117. // At least one of the values is NaN.
  118. if (IsNaN(m_value))
  119. return (IsNaN(f) ? 0 : -1);
  120. else // f is NaN.
  121. return 1;
  122. }
  123. throw new ArgumentException(SR.Arg_MustBeSingle);
  124. }
  125. public int CompareTo(float value)
  126. {
  127. if (m_value < value) return -1;
  128. if (m_value > value) return 1;
  129. if (m_value == value) return 0;
  130. // At least one of the values is NaN.
  131. if (IsNaN(m_value))
  132. return (IsNaN(value) ? 0 : -1);
  133. else // f is NaN.
  134. return 1;
  135. }
  136. [NonVersionable]
  137. public static bool operator ==(float left, float right)
  138. {
  139. return left == right;
  140. }
  141. [NonVersionable]
  142. public static bool operator !=(float left, float right)
  143. {
  144. return left != right;
  145. }
  146. [NonVersionable]
  147. public static bool operator <(float left, float right)
  148. {
  149. return left < right;
  150. }
  151. [NonVersionable]
  152. public static bool operator >(float left, float right)
  153. {
  154. return left > right;
  155. }
  156. [NonVersionable]
  157. public static bool operator <=(float left, float right)
  158. {
  159. return left <= right;
  160. }
  161. [NonVersionable]
  162. public static bool operator >=(float left, float right)
  163. {
  164. return left >= right;
  165. }
  166. public override bool Equals(object obj)
  167. {
  168. if (!(obj is float))
  169. {
  170. return false;
  171. }
  172. float temp = ((float)obj).m_value;
  173. if (temp == m_value)
  174. {
  175. return true;
  176. }
  177. return IsNaN(temp) && IsNaN(m_value);
  178. }
  179. public bool Equals(float obj)
  180. {
  181. if (obj == m_value)
  182. {
  183. return true;
  184. }
  185. return IsNaN(obj) && IsNaN(m_value);
  186. }
  187. public override int GetHashCode()
  188. {
  189. var bits = Unsafe.As<float, int>(ref Unsafe.AsRef(in m_value));
  190. // Optimized check for IsNan() || IsZero()
  191. if (((bits - 1) & 0x7FFFFFFF) >= 0x7F800000)
  192. {
  193. // Ensure that all NaNs and both zeros have the same hash code
  194. bits &= 0x7F800000;
  195. }
  196. return bits;
  197. }
  198. public override string ToString()
  199. {
  200. return Number.FormatSingle(m_value, null, NumberFormatInfo.CurrentInfo);
  201. }
  202. public string ToString(IFormatProvider provider)
  203. {
  204. return Number.FormatSingle(m_value, null, NumberFormatInfo.GetInstance(provider));
  205. }
  206. public string ToString(string format)
  207. {
  208. return Number.FormatSingle(m_value, format, NumberFormatInfo.CurrentInfo);
  209. }
  210. public string ToString(string format, IFormatProvider provider)
  211. {
  212. return Number.FormatSingle(m_value, format, NumberFormatInfo.GetInstance(provider));
  213. }
  214. public bool TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format = default, IFormatProvider provider = null)
  215. {
  216. return Number.TryFormatSingle(m_value, format, NumberFormatInfo.GetInstance(provider), destination, out charsWritten);
  217. }
  218. // Parses a float from a String in the given style. If
  219. // a NumberFormatInfo isn't specified, the current culture's
  220. // NumberFormatInfo is assumed.
  221. //
  222. // This method will not throw an OverflowException, but will return
  223. // PositiveInfinity or NegativeInfinity for a number that is too
  224. // large or too small.
  225. //
  226. public static float Parse(string s)
  227. {
  228. if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
  229. return Number.ParseSingle(s, NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.CurrentInfo);
  230. }
  231. public static float Parse(string s, NumberStyles style)
  232. {
  233. NumberFormatInfo.ValidateParseStyleFloatingPoint(style);
  234. if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
  235. return Number.ParseSingle(s, style, NumberFormatInfo.CurrentInfo);
  236. }
  237. public static float Parse(string s, IFormatProvider provider)
  238. {
  239. if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
  240. return Number.ParseSingle(s, NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.GetInstance(provider));
  241. }
  242. public static float Parse(string s, NumberStyles style, IFormatProvider provider)
  243. {
  244. NumberFormatInfo.ValidateParseStyleFloatingPoint(style);
  245. if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
  246. return Number.ParseSingle(s, style, NumberFormatInfo.GetInstance(provider));
  247. }
  248. public static float Parse(ReadOnlySpan<char> s, NumberStyles style = NumberStyles.Float | NumberStyles.AllowThousands, IFormatProvider provider = null)
  249. {
  250. NumberFormatInfo.ValidateParseStyleFloatingPoint(style);
  251. return Number.ParseSingle(s, style, NumberFormatInfo.GetInstance(provider));
  252. }
  253. public static bool TryParse(string s, out float result)
  254. {
  255. if (s == null)
  256. {
  257. result = 0;
  258. return false;
  259. }
  260. return TryParse((ReadOnlySpan<char>)s, NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.CurrentInfo, out result);
  261. }
  262. public static bool TryParse(ReadOnlySpan<char> s, out float result)
  263. {
  264. return TryParse(s, NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.CurrentInfo, out result);
  265. }
  266. public static bool TryParse(string s, NumberStyles style, IFormatProvider provider, out float result)
  267. {
  268. NumberFormatInfo.ValidateParseStyleFloatingPoint(style);
  269. if (s == null)
  270. {
  271. result = 0;
  272. return false;
  273. }
  274. return TryParse((ReadOnlySpan<char>)s, style, NumberFormatInfo.GetInstance(provider), out result);
  275. }
  276. public static bool TryParse(ReadOnlySpan<char> s, NumberStyles style, IFormatProvider provider, out float result)
  277. {
  278. NumberFormatInfo.ValidateParseStyleFloatingPoint(style);
  279. return TryParse(s, style, NumberFormatInfo.GetInstance(provider), out result);
  280. }
  281. private static bool TryParse(ReadOnlySpan<char> s, NumberStyles style, NumberFormatInfo info, out float result)
  282. {
  283. return Number.TryParseSingle(s, style, info, out result);
  284. }
  285. //
  286. // IConvertible implementation
  287. //
  288. public TypeCode GetTypeCode()
  289. {
  290. return TypeCode.Single;
  291. }
  292. bool IConvertible.ToBoolean(IFormatProvider provider)
  293. {
  294. return Convert.ToBoolean(m_value);
  295. }
  296. char IConvertible.ToChar(IFormatProvider provider)
  297. {
  298. throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Single", "Char"));
  299. }
  300. sbyte IConvertible.ToSByte(IFormatProvider provider)
  301. {
  302. return Convert.ToSByte(m_value);
  303. }
  304. byte IConvertible.ToByte(IFormatProvider provider)
  305. {
  306. return Convert.ToByte(m_value);
  307. }
  308. short IConvertible.ToInt16(IFormatProvider provider)
  309. {
  310. return Convert.ToInt16(m_value);
  311. }
  312. ushort IConvertible.ToUInt16(IFormatProvider provider)
  313. {
  314. return Convert.ToUInt16(m_value);
  315. }
  316. int IConvertible.ToInt32(IFormatProvider provider)
  317. {
  318. return Convert.ToInt32(m_value);
  319. }
  320. uint IConvertible.ToUInt32(IFormatProvider provider)
  321. {
  322. return Convert.ToUInt32(m_value);
  323. }
  324. long IConvertible.ToInt64(IFormatProvider provider)
  325. {
  326. return Convert.ToInt64(m_value);
  327. }
  328. ulong IConvertible.ToUInt64(IFormatProvider provider)
  329. {
  330. return Convert.ToUInt64(m_value);
  331. }
  332. float IConvertible.ToSingle(IFormatProvider provider)
  333. {
  334. return m_value;
  335. }
  336. double IConvertible.ToDouble(IFormatProvider provider)
  337. {
  338. return Convert.ToDouble(m_value);
  339. }
  340. decimal IConvertible.ToDecimal(IFormatProvider provider)
  341. {
  342. return Convert.ToDecimal(m_value);
  343. }
  344. DateTime IConvertible.ToDateTime(IFormatProvider provider)
  345. {
  346. throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Single", "DateTime"));
  347. }
  348. object IConvertible.ToType(Type type, IFormatProvider provider)
  349. {
  350. return Convert.DefaultToType((IConvertible)this, type, provider);
  351. }
  352. }
  353. }