Accuracy issues when reading data from an input file
2 views (last 30 days)
Show older comments
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 Comments
Accepted Answer
Andrew Newell
on 8 Jan 2012
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 Comments
Walter Roberson
on 9 Jan 2012
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]
More Answers (0)
See Also
Categories
Find more on Logical in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!