Double.cs 15 KB

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