3 // Copyright (c) Microsoft Corporation. All rights reserved.
6 /*============================================================
11 ** Purpose: A representation of an IEEE double precision
12 ** floating point number.
15 ===========================================================*/
19 using System.Globalization;
21 /// using System.Numerics;
23 using System.Runtime.InteropServices;
24 using System.Runtime.CompilerServices;
25 using System.Runtime.ConstrainedExecution;
26 using System.Diagnostics.Contracts;
29 [StructLayout(LayoutKind.Sequential)]
30 [System.Runtime.InteropServices.ComVisible(true)]
32 public struct Double : IComparable, IFormattable, IConvertible
33 , IComparable<Double>, IEquatable<Double>
34 /// , IArithmetic<Double>
36 public struct Double : IComparable, IFormattable, IConvertible
39 internal double m_value;
44 public const double MinValue = -1.7976931348623157E+308;
45 public const double MaxValue = 1.7976931348623157E+308;
47 // Note Epsilon should be a double whose hex representation is 0x1
48 // on little endian machines.
49 public const double Epsilon = 4.9406564584124654E-324;
50 public const double NegativeInfinity = (double)-1.0 / (double)(0.0);
51 public const double PositiveInfinity = (double)1.0 / (double)(0.0);
52 public const double NaN = (double)0.0 / (double)0.0;
54 internal static double NegativeZero = BitConverter.Int64BitsToDouble(unchecked((long)0x8000000000000000));
57 [System.Security.SecuritySafeCritical] // auto-generated
58 [System.Runtime.Versioning.NonVersionable]
59 public unsafe static bool IsInfinity(double d) {
60 return (*(long*)(&d) & 0x7FFFFFFFFFFFFFFF) == 0x7FF0000000000000;
64 [System.Runtime.Versioning.NonVersionable]
65 public static bool IsPositiveInfinity(double d) {
66 //Jit will generate inlineable code with this
67 if (d == double.PositiveInfinity)
78 [System.Runtime.Versioning.NonVersionable]
79 public static bool IsNegativeInfinity(double d) {
80 //Jit will generate inlineable code with this
81 if (d == double.NegativeInfinity)
92 [System.Security.SecuritySafeCritical] // auto-generated
93 internal unsafe static bool IsNegative(double d) {
94 return (*(UInt64*)(&d) & 0x8000000000000000) == 0x8000000000000000;
98 [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
99 [System.Security.SecuritySafeCritical]
100 [System.Runtime.Versioning.NonVersionable]
101 public unsafe static bool IsNaN(double d)
103 return (*(UInt64*)(&d) & 0x7FFFFFFFFFFFFFFFL) > 0x7FF0000000000000L;
108 [System.Runtime.Versioning.NonVersionable]
109 [MethodImpl(MethodImplOptions.AggressiveInlining)]
110 public unsafe static bool IsFinite(double d)
112 var bits = BitConverter.DoubleToInt64Bits(d);
113 return (bits & 0x7FFFFFFFFFFFFFFF) < 0x7FF0000000000000;
117 // Compares this object to another object, returning an instance of System.Relation.
118 // Null is considered less than any instance.
120 // If object is not of type Double, this method throws an ArgumentException.
122 // Returns a value less than zero if this object
124 public int CompareTo(Object value) {
128 if (value is Double) {
129 double d = (double)value;
130 if (m_value < d) return -1;
131 if (m_value > d) return 1;
132 if (m_value == d) return 0;
134 // At least one of the values is NaN.
136 return (IsNaN(d) ? 0 : -1);
140 throw new ArgumentException(Environment.GetResourceString("Arg_MustBeDouble"));
143 public int CompareTo(Double value) {
144 if (m_value < value) return -1;
145 if (m_value > value) return 1;
146 if (m_value == value) return 0;
148 // At least one of the values is NaN.
150 return (IsNaN(value) ? 0 : -1);
155 // True if obj is another Double with the same value as the current instance. This is
156 // a method of object equality, that only returns true if obj is also a double.
157 public override bool Equals(Object obj) {
158 if (!(obj is Double)) {
161 double temp = ((Double)obj).m_value;
162 // This code below is written this way for performance reasons i.e the != and == check is intentional.
163 if (temp == m_value) {
166 return IsNaN(temp) && IsNaN(m_value);
169 [System.Runtime.Versioning.NonVersionable]
170 public static bool operator ==(Double left, Double right) {
171 return left == right;
174 [System.Runtime.Versioning.NonVersionable]
175 public static bool operator !=(Double left, Double right) {
176 return left != right;
179 [System.Runtime.Versioning.NonVersionable]
180 public static bool operator <(Double left, Double right) {
184 [System.Runtime.Versioning.NonVersionable]
185 public static bool operator >(Double left, Double right) {
189 [System.Runtime.Versioning.NonVersionable]
190 public static bool operator <=(Double left, Double right) {
191 return left <= right;
194 [System.Runtime.Versioning.NonVersionable]
195 public static bool operator >=(Double left, Double right) {
196 return left >= right;
199 public bool Equals(Double obj)
201 if (obj == m_value) {
204 return IsNaN(obj) && IsNaN(m_value);
207 //The hashcode for a double is the absolute value of the integer representation
210 [System.Security.SecuritySafeCritical]
211 public unsafe override int GetHashCode() {
214 // Ensure that 0 and -0 have the same hash code
217 long value = *(long*)(&d);
218 return unchecked((int)value) ^ ((int)(value >> 32));
221 [System.Security.SecuritySafeCritical] // auto-generated
222 public override String ToString() {
223 Contract.Ensures(Contract.Result<String>() != null);
224 return Number.FormatDouble(m_value, null, NumberFormatInfo.CurrentInfo);
227 [System.Security.SecuritySafeCritical] // auto-generated
228 public String ToString(String format) {
229 Contract.Ensures(Contract.Result<String>() != null);
230 return Number.FormatDouble(m_value, format, NumberFormatInfo.CurrentInfo);
233 [System.Security.SecuritySafeCritical] // auto-generated
234 public String ToString(IFormatProvider provider) {
235 Contract.Ensures(Contract.Result<String>() != null);
236 return Number.FormatDouble(m_value, null, NumberFormatInfo.GetInstance(provider));
239 [System.Security.SecuritySafeCritical] // auto-generated
240 public String ToString(String format, IFormatProvider provider) {
241 Contract.Ensures(Contract.Result<String>() != null);
242 return Number.FormatDouble(m_value, format, NumberFormatInfo.GetInstance(provider));
245 public static double Parse(String s) {
246 return Parse(s, NumberStyles.Float| NumberStyles.AllowThousands, NumberFormatInfo.CurrentInfo);
249 public static double Parse(String s, NumberStyles style) {
250 NumberFormatInfo.ValidateParseStyleFloatingPoint(style);
251 return Parse(s, style, NumberFormatInfo.CurrentInfo);
254 public static double Parse(String s, IFormatProvider provider) {
255 return Parse(s, NumberStyles.Float| NumberStyles.AllowThousands, NumberFormatInfo.GetInstance(provider));
258 public static double Parse(String s, NumberStyles style, IFormatProvider provider) {
259 NumberFormatInfo.ValidateParseStyleFloatingPoint(style);
260 return Parse(s, style, NumberFormatInfo.GetInstance(provider));
263 // Parses a double from a String in the given style. If
264 // a NumberFormatInfo isn't specified, the current culture's
265 // NumberFormatInfo is assumed.
267 // This method will not throw an OverflowException, but will return
268 // PositiveInfinity or NegativeInfinity for a number that is too
269 // large or too small.
271 private static double Parse(String s, NumberStyles style, NumberFormatInfo info) {
272 return Number.ParseDouble(s, style, info);
275 public static bool TryParse(String s, out double result) {
276 return TryParse(s, NumberStyles.Float| NumberStyles.AllowThousands, NumberFormatInfo.CurrentInfo, out result);
279 public static bool TryParse(String s, NumberStyles style, IFormatProvider provider, out double result) {
280 NumberFormatInfo.ValidateParseStyleFloatingPoint(style);
281 return TryParse(s, style, NumberFormatInfo.GetInstance(provider), out result);
284 private static bool TryParse(String s, NumberStyles style, NumberFormatInfo info, out double result) {
289 bool success = Number.TryParseDouble(s, style, info, out result);
291 String sTrim = s.Trim();
292 if (sTrim.Equals(info.PositiveInfinitySymbol)) {
293 result = PositiveInfinity;
294 } else if (sTrim.Equals(info.NegativeInfinitySymbol)) {
295 result = NegativeInfinity;
296 } else if (sTrim.Equals(info.NaNSymbol)) {
299 return false; // We really failed
305 // IConvertible implementation
308 public TypeCode GetTypeCode() {
309 return TypeCode.Double;
313 bool IConvertible.ToBoolean(IFormatProvider provider) {
314 return Convert.ToBoolean(m_value);
318 char IConvertible.ToChar(IFormatProvider provider) {
319 throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "Double", "Char"));
323 sbyte IConvertible.ToSByte(IFormatProvider provider) {
324 return Convert.ToSByte(m_value);
328 byte IConvertible.ToByte(IFormatProvider provider) {
329 return Convert.ToByte(m_value);
333 short IConvertible.ToInt16(IFormatProvider provider) {
334 return Convert.ToInt16(m_value);
338 ushort IConvertible.ToUInt16(IFormatProvider provider) {
339 return Convert.ToUInt16(m_value);
343 int IConvertible.ToInt32(IFormatProvider provider) {
344 return Convert.ToInt32(m_value);
348 uint IConvertible.ToUInt32(IFormatProvider provider) {
349 return Convert.ToUInt32(m_value);
353 long IConvertible.ToInt64(IFormatProvider provider) {
354 return Convert.ToInt64(m_value);
358 ulong IConvertible.ToUInt64(IFormatProvider provider) {
359 return Convert.ToUInt64(m_value);
363 float IConvertible.ToSingle(IFormatProvider provider) {
364 return Convert.ToSingle(m_value);
368 double IConvertible.ToDouble(IFormatProvider provider) {
373 Decimal IConvertible.ToDecimal(IFormatProvider provider) {
374 return Convert.ToDecimal(m_value);
378 DateTime IConvertible.ToDateTime(IFormatProvider provider) {
379 throw new InvalidCastException(Environment.GetResourceString("InvalidCast_FromTo", "Double", "DateTime"));
383 Object IConvertible.ToType(Type type, IFormatProvider provider) {
384 return Convert.DefaultToType((IConvertible)this, type, provider);
389 /// // IArithmetic<Double> implementation
392 /// /// <internalonly/>
393 /// Double IArithmetic<Double>.AbsoluteValue(out bool overflowed) {
394 /// Double abs = (m_value < 0 ? -m_value : m_value);
395 /// overflowed = IsInfinity(abs) || IsNaN(abs);
399 /// /// <internalonly/>
400 /// Double IArithmetic<Double>.Negate(out bool overflowed) {
401 /// Double neg= -m_value;
402 /// overflowed = IsInfinity(neg) || IsNaN(neg);
406 /// /// <internalonly/>
407 /// Double IArithmetic<Double>.Sign(out bool overflowed) {
408 /// overflowed = IsNaN(m_value);
409 /// if (overflowed) {
412 /// return (m_value >= 0 ? (m_value == 0 ? 0 : 1) : -1);
415 /// /// <internalonly/>
416 /// Double IArithmetic<Double>.Add(Double addend, out bool overflowed) {
417 /// Double s = m_value + addend;
418 /// overflowed = IsInfinity(s) || IsNaN(s);
422 /// /// <internalonly/>
423 /// Double IArithmetic<Double>.Subtract(Double subtrahend, out bool overflowed) {
424 /// Double s = m_value - subtrahend;
425 /// overflowed = IsInfinity(s) || IsNaN(s);
429 /// /// <internalonly/>
430 /// Double IArithmetic<Double>.Multiply(Double multiplier, out bool overflowed) {
431 /// Double s = m_value * multiplier;
432 /// overflowed = IsInfinity(s) || IsNaN(s);
437 /// /// <internalonly/>
438 /// Double IArithmetic<Double>.Divide(Double divisor, out bool overflowed) {
439 /// Double s = m_value / divisor;
440 /// overflowed = IsInfinity(s) || IsNaN(s);
444 /// /// <internalonly/>
445 /// Double IArithmetic<Double>.DivideRemainder(Double divisor, out Double remainder, out bool overflowed) {
446 /// remainder = m_value % divisor;
447 /// Double s = m_value / divisor;
448 /// overflowed = IsInfinity(s) || IsInfinity(remainder) || IsNaN(s) || IsNaN(remainder);
452 /// /// <internalonly/>
453 /// Double IArithmetic<Double>.Remainder(Double divisor, out bool overflowed) {
454 /// Double d = m_value % divisor;
455 /// overflowed = IsInfinity(d) || IsNaN(d);
459 /// /// <internalonly/>
460 /// ArithmeticDescriptor<Double> IArithmetic<Double>.GetDescriptor() {
461 /// if (s_descriptor == null) {
462 /// s_descriptor = new DoubleArithmeticDescriptor( ArithmeticCapabilities.One
463 /// | ArithmeticCapabilities.Zero
464 /// | ArithmeticCapabilities.MaxValue
465 /// | ArithmeticCapabilities.MinValue
466 /// | ArithmeticCapabilities.PositiveInfinity
467 /// | ArithmeticCapabilities.NegativeInfinity);
469 /// return s_descriptor;
472 /// private static DoubleArithmeticDescriptor s_descriptor;
474 /// class DoubleArithmeticDescriptor : ArithmeticDescriptor<Double> {
475 /// public DoubleArithmeticDescriptor(ArithmeticCapabilities capabilities) : base(capabilities) {}
477 /// public override Double One {
479 /// return (Double) 1;
483 /// public override Double Zero {
485 /// return (Double) 0;
489 /// public override Double MinValue {
491 /// return Double.MinValue;
495 /// public override Double MaxValue {
497 /// return Double.MaxValue;
501 /// public override Double PositiveInfinity {
503 /// return Double.PositiveInfinity;
507 /// public override Double NegativeInfinity {
509 /// return Double.NegativeInfinity;
514 ///#endif // #if GENERICS_WORK