[英]retaining the precison after reading and writing the double values to binary file
我正在創建一個二進制文件。 文件的內容是雙精度值。 當我使用二進制讀取器提取雙精度值時,小數點后的某些值不匹配
例如:寫入文件的值。 -0.0139519833028316
從文件中提取的值。 -0.0139519833028317
我如何避免這種不一致?
aStreamWriter.WriteLine(double values);
//to read the data ,
BinaryReader aBinaryReader = new BinaryReader();
int points_length = CurveCount * VectorLength * 2 * VoxelIndex.Length * 2;
double[] points = new double[points_length];
for (int i = 0; i < points_length; i++)
points[i] = aBinaryReader.ReadDouble();
for(int i =0; i < points_length; i++) {
// then write the points values to a file
}
確實是前后矛盾嗎? 從概念上講,double是逼近實數。 考慮到原始測量中的誤差,該數字有效嗎? 在這種情況下,它們不是真正的“相同”數字嗎?
編輯:
通過您的評論,問題變得很明顯。 StreamWriter
是文本 StreamWriter
器。 對aStreamWriter.WriteLine(double)
的調用正在編寫text 。 坦白說,您很幸運能將所有東西還回來。
原版的
工作正常:
double d = -0.0139519833028316;
byte[] raw;
using (var ms = new MemoryStream())
{
using (var writer = new BinaryWriter(ms))
{
writer.Write(d);
}
raw = ms.ToArray();
}
double newVal;
using(var ms = new MemoryStream(raw))
using (var reader = new BinaryReader(ms))
{
newVal = reader.ReadDouble();
}
Console.WriteLine(newVal == d); // True
我懷疑您只是看到double
舍入奇數,這與讀/寫代碼完全無關。
基本上,您有雙重數據類型的問題。 Double基本上是以2(2 ^ 64)為底的數字的近似值。 如果沒有可以計算的精確數字(從10開始),則它選擇關閉數字,可以將其保存為雙精度數。
如果您需要超精確的方法來保存數字,請將其另存為字符串。 取決於數學或對數字的處理,您始終可以編寫自己的函數。
將“金錢價值”保存為數據庫中的浮動貨幣正在發生類似的事情。 他們使用money數據類型,因為float並不是真正可行的方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.