Matlab Floating point question
1 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Jan
2012-9-12
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 个评论
更多回答(2 个)
Kevin Claytor
2012-9-12
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 个评论
Kevin Claytor
2012-9-12
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
2012-9-12
编辑:Matt Fig
2012-9-12
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 个评论
Matt Fig
2012-9-12
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).
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Creating and Concatenating Matrices 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!