Matlab Floating point question
이전 댓글 표시
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)');
채택된 답변
추가 답변 (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
Darin McCoy
2012년 9월 12일
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?
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
Darin McCoy
2012년 9월 12일
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).
Walter Roberson
2012년 9월 13일
Darin, you can use the (optional, extra cost) Fixed Point Toolbox.
카테고리
도움말 센터 및 File Exchange에서 Logical에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!