Single.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  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. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  188. public override int GetHashCode()
  189. {
  190. var bits = Unsafe.As<float, int>(ref Unsafe.AsRef(in m_value));
  191. // Optimized check for IsNan() || IsZero()
  192. if (((bits - 1) & 0x7FFFFFFF) >= 0x7F800000)
  193. {
  194. // Ensure that all NaNs and both zeros have the same hash code
  195. bits &= 0x7F800000;
  196. }
  197. return bits;
  198. }
  199. public override string ToString()
  200. {
  201. return Number.FormatSingle(m_value, null, NumberFormatInfo.CurrentInfo);
  202. }
  203. public string ToString(IFormatProvider? provider)
  204. {
  205. return Number.FormatSingle(m_value, null, NumberFormatInfo.GetInstance(provider));
  206. }
  207. public string ToString(string? format)
  208. {
  209. return Number.FormatSingle(m_value, format, NumberFormatInfo.CurrentInfo);
  210. }
  211. public string ToString(string? format, IFormatProvider? provider)
  212. {
  213. return Number.FormatSingle(m_value, format, NumberFormatInfo.GetInstance(provider));
  214. }
  215. public bool TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format = default, IFormatProvider? provider = null)
  216. {
  217. return Number.TryFormatSingle(m_value, format, NumberFormatInfo.GetInstance(provider), destination, out charsWritten);
  218. }
  219. // Parses a float from a String in the given style. If
  220. // a NumberFormatInfo isn't specified, the current culture's
  221. // NumberFormatInfo is assumed.
  222. //
  223. // This method will not throw an OverflowException, but will return
  224. // PositiveInfinity or NegativeInfinity for a number that is too
  225. // large or too small.
  226. //
  227. public static float Parse(string s)
  228. {
  229. if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
  230. return Number.ParseSingle(s, NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.CurrentInfo);
  231. }
  232. public static float Parse(string s, NumberStyles style)
  233. {
  234. NumberFormatInfo.ValidateParseStyleFloatingPoint(style);
  235. if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
  236. return Number.ParseSingle(s, style, NumberFormatInfo.CurrentInfo);
  237. }
  238. public static float Parse(string s, IFormatProvider? provider)
  239. {
  240. if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
  241. return Number.ParseSingle(s, NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.GetInstance(provider));
  242. }
  243. public static float Parse(string s, NumberStyles style, IFormatProvider? provider)
  244. {
  245. NumberFormatInfo.ValidateParseStyleFloatingPoint(style);
  246. if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s);
  247. return Number.ParseSingle(s, style, NumberFormatInfo.GetInstance(provider));
  248. }
  249. public static float Parse(ReadOnlySpan<char> s, NumberStyles style = NumberStyles.Float | NumberStyles.AllowThousands, IFormatProvider? provider = null)
  250. {
  251. NumberFormatInfo.ValidateParseStyleFloatingPoint(style);
  252. return Number.ParseSingle(s, style, NumberFormatInfo.GetInstance(provider));
  253. }
  254. public static bool TryParse(string? s, out float result)
  255. {
  256. if (s == null)
  257. {
  258. result = 0;
  259. return false;
  260. }
  261. return TryParse((ReadOnlySpan<char>)s, NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.CurrentInfo, out result);
  262. }
  263. public static bool TryParse(ReadOnlySpan<char> s, out float result)
  264. {
  265. return TryParse(s, NumberStyles.Float | NumberStyles.AllowThousands, NumberFormatInfo.CurrentInfo, out result);
  266. }
  267. public static bool TryParse(string? s, NumberStyles style, IFormatProvider? provider, out float result)
  268. {
  269. NumberFormatInfo.ValidateParseStyleFloatingPoint(style);
  270. if (s == null)
  271. {
  272. result = 0;
  273. return false;
  274. }
  275. return TryParse((ReadOnlySpan<char>)s, style, NumberFormatInfo.GetInstance(provider), out result);
  276. }
  277. public static bool TryParse(ReadOnlySpan<char> s, NumberStyles style, IFormatProvider? provider, out float result)
  278. {
  279. NumberFormatInfo.ValidateParseStyleFloatingPoint(style);
  280. return TryParse(s, style, NumberFormatInfo.GetInstance(provider), out result);
  281. }
  282. private static bool TryParse(ReadOnlySpan<char> s, NumberStyles style, NumberFormatInfo info, out float result)
  283. {
  284. return Number.TryParseSingle(s, style, info, out result);
  285. }
  286. //
  287. // IConvertible implementation
  288. //
  289. public TypeCode GetTypeCode()
  290. {
  291. return TypeCode.Single;
  292. }
  293. bool IConvertible.ToBoolean(IFormatProvider? provider)
  294. {
  295. return Convert.ToBoolean(m_value);
  296. }
  297. char IConvertible.ToChar(IFormatProvider? provider)
  298. {
  299. throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Single", "Char"));
  300. }
  301. sbyte IConvertible.ToSByte(IFormatProvider? provider)
  302. {
  303. return Convert.ToSByte(m_value);
  304. }
  305. byte IConvertible.ToByte(IFormatProvider? provider)
  306. {
  307. return Convert.ToByte(m_value);
  308. }
  309. short IConvertible.ToInt16(IFormatProvider? provider)
  310. {
  311. return Convert.ToInt16(m_value);
  312. }
  313. ushort IConvertible.ToUInt16(IFormatProvider? provider)
  314. {
  315. return Convert.ToUInt16(m_value);
  316. }
  317. int IConvertible.ToInt32(IFormatProvider? provider)
  318. {
  319. return Convert.ToInt32(m_value);
  320. }
  321. uint IConvertible.ToUInt32(IFormatProvider? provider)
  322. {
  323. return Convert.ToUInt32(m_value);
  324. }
  325. long IConvertible.ToInt64(IFormatProvider? provider)
  326. {
  327. return Convert.ToInt64(m_value);
  328. }
  329. ulong IConvertible.ToUInt64(IFormatProvider? provider)
  330. {
  331. return Convert.ToUInt64(m_value);
  332. }
  333. float IConvertible.ToSingle(IFormatProvider? provider)
  334. {
  335. return m_value;
  336. }
  337. double IConvertible.ToDouble(IFormatProvider? provider)
  338. {
  339. return Convert.ToDouble(m_value);
  340. }
  341. decimal IConvertible.ToDecimal(IFormatProvider? provider)
  342. {
  343. return Convert.ToDecimal(m_value);
  344. }
  345. DateTime IConvertible.ToDateTime(IFormatProvider? provider)
  346. {
  347. throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "Single", "DateTime"));
  348. }
  349. object IConvertible.ToType(Type type, IFormatProvider? provider)
  350. {
  351. return Convert.DefaultToType((IConvertible)this, type, provider);
  352. }
  353. }
  354. }