雙精度浮點的維基百科頁面是在這裏:http://en.wikipedia.org/wiki/Double_precision_floating-point_format
爲了好玩,我寫了一些代碼,以擺脫double
格式的二進制表示,遞減尾數和重新組成產生的兩倍。由於尾數隱含,我們必須檢查它並相應地修改指數,並且可能會在極限附近失效。
下面的代碼:
public static double PrevDouble(double src)
{
// check for special values:
if (double.IsInfinity(src) || double.IsNaN(src))
return src;
if (src == 0)
return -double.MinValue;
// get bytes from double
byte[] srcbytes = System.BitConverter.GetBytes(src);
// extract components
byte sign = (byte)(srcbytes[7] & 0x80);
ulong exp = ((((ulong)srcbytes[7]) & 0x7F) << 4) + (((ulong)srcbytes[6] >> 4) & 0x0F);
ulong mant = ((ulong)1 << 52) | (((ulong)srcbytes[6] & 0x0F) << 48) | (((ulong)srcbytes[5]) << 40) | (((ulong)srcbytes[4]) << 32) | (((ulong)srcbytes[3]) << 24) | (((ulong)srcbytes[2]) << 16) | (((ulong)srcbytes[1]) << 8) | ((ulong)srcbytes[0]);
// decrement mantissa
--mant;
// check if implied bit has been removed and shift if so
if ((mant & ((ulong)1 << 52)) == 0)
{
mant <<= 1;
exp--;
}
// build byte representation of modified value
byte[] bytes = new byte[8];
bytes[7] = (byte)((ulong)sign | ((exp >> 4) & 0x7F));
bytes[6] = (byte)((((ulong)exp & 0x0F) << 4) | ((mant >> 48) & 0x0F));
bytes[5] = (byte)((mant >> 40) & 0xFF);
bytes[4] = (byte)((mant >> 32) & 0xFF);
bytes[3] = (byte)((mant >> 24) & 0xFF);
bytes[2] = (byte)((mant >> 16) & 0xFF);
bytes[1] = (byte)((mant >> 8) & 0xFF);
bytes[0] = (byte)(mant & 0xFF);
// convert back to double and return
double res = System.BitConverter.ToDouble(bytes, 0);
return res;
}
所有這一切都爲您提供了一個值是由在尾數最低位發生變化的初始值不同......在理論上:)
這是一個測試:
public static Main(string[] args)
{
double test = 1.0/3;
double prev = PrevDouble(test);
Console.WriteLine("{0:r}, {1:r}, {2:r}", test, prev, test - prev);
}
給我的電腦上,結果如下:
0.33333333333333331, 0.33333333333333326, 5.5511151231257827E-17
區別在那裏,但可能低於舍入閾值。表達test == prev
的值爲false不過,並沒有如上圖所示:)
如果你除以10 – Hogan 2013-03-11 03:22:03
我覺得你的問題已經在這裏回答:http://stackoverflow.com/a/2283565/1715579。 – 2013-03-11 03:22:37