Matlab Floating point question
2 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
I would like to create a time array with the same samplingrate...the top example works...the bottom does not....do you know why this happens???
start = single(0);
endit = single(199532);
samprate = single(8.333333);
%Works just fine
figure(1)
subplot(2,1,1)
plot(diff(start:endit)/samprate)
title('Sampling rate is consistently 0.12 (Correct)');
%Doesn't work just fine
array = (start:endit)/samprate;
subplot(2,1,2)
plot(diff(array))
title('Sampling rate is NOT consistently 0.12 (Incorrect)');
0 commentaires
Réponse acceptée
Jan
le 12 Sep 2012
The correct term to describe this is not "incorrect" but "inaccurate". With the limited precision of floating point values, both results are absolute correct. But the 2nd example shows the effects of floating point arithmetic. See the famous example: 0.3 - 0.2 - 0.1 == 0 ==> FALSE! This has been discussed such frequently, that you find it in the frequently asked questions.
0 commentaires
Plus de réponses (2)
Kevin Claytor
le 12 Sep 2012
Your first one is perhaps not producing the results you expect it to
plot(diff(start:endit)/samprate)
vs.
plot(diff( (start:endit)/samprate ) )
% Identical to;
array = (start:endit)/samprate;
plot(diff(array))
2 commentaires
Kevin Claytor
le 12 Sep 2012
Perhaps I misunderstand what you mean. You are not comparing two identical expressions - in the first;
plot( diff(start:endit) / samprate )
diff operates on the integer array (producing one each time, since this is presumably exact integer subtraction), then the result is divided by samprate. In the second;
plot(diff( (start:endit)/samprate ) )
diff operates on [the integer array divided by the sampling rate]. The term in brackets is now a set of floating point values and will not be exact, and diff starts to produce some real differences. Is this your question?
Matt Fig
le 12 Sep 2012
Modifié(e) : Matt Fig
le 12 Sep 2012
In the first example, you are dividing a bunch of 1s by the sample rate. In the second, you are dividing some small numbers and some large numbers by the sample rate.
In FP, the larger the difference between the magnitude of the numerator and denominator, the larger the resulting FP error.
Try it out:
samprate = single(25/3);
f = @(N) abs((3*N)/25-N/samprate);
f(1)
f(199532)
3 commentaires
Matt Fig
le 12 Sep 2012
No FP error? Then you will have to work only with symbolic values. This will be slower, certain problems may not have solutions, and certain functionality may not be available.
It seems to me that you just learn to live with the limitations of FP arithmetic and do things the smart way (like the top example you provide).
Voir également
Catégories
En savoir plus sur Logical dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!