Accuracy issues when reading data from an input file
조회 수: 1 (최근 30일)
이전 댓글 표시
Hi
A simple question. Please find the code below. I'm experiencing an accuracy issue. Tried %f, %e and %g in fscanf but none solves my problem.
Input file contains:
0
0.1
0.2
0.3
0.4
0.1
0.2
0.3
0.4
0.5
Code:
meshf = fopen('./test_accuracy.dat', 'r');
all = fscanf(meshf, '%f', [1,10]);
all = all';
startN = all(1:5);
endN = all(6:10);
dl = endN - startN;
for j = 1:4
dl_check(j,1) = dl(j) - dl(j+1);
end
fclose(meshf)
Output: dl =
0.100000000000000
0.100000000000000
0.100000000000000
0.100000000000000
0.100000000000000
dl_check =
1.0e-016 *
0
0.277555756156289
-0.555111512312578
0.555111512312578
My Question: Typically we would expect dl_check to be all zeros right!? What format flags should I use to prevent this problem.
Many Thanks
Amar
댓글 수: 0
채택된 답변
Andrew Newell
2012년 1월 8일
You can't do better than that because the decimal numbers are really represented by binary numbers, which can't represent a lot of these fractions any better. If you try rounding the numbers to the first decimal, you'll get the same answer:
all - round(all*10)/10
returns all zeros.
For most purposes that's accurate enough: all the numbers in dl_check are at most 2*eps in magnitude. If you need to do better than that , you'll need extended precision arithmetic (as in, for example, the Symbolic Toolbox).
댓글 수: 10
Walter Roberson
2012년 1월 9일
You will NOT be able to get rid of the problem of that 17th decimal place. Not as long as you are using binary floating point arithmetic. The problem is inherent in using any number base other than one which is an exact multiple of the denominator of the fraction you are trying to represent. Try, for example, *exactly* representing 1/7 in base 10 with using only a finite number of positions. Or exactly representing 1/3 in base 2, 4, or 5 -- but 1/3 in base 6 is no problem as [1/3 decimal] = [0.2 senary]
추가 답변 (0개)
참고 항목
카테고리
Help Center 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!