How to get rid of small difference (or error) when I multiply 0.1?

조회 수: 2 (최근 30일)
Sangmin Lee
Sangmin Lee 2021년 6월 24일
댓글: Sangmin Lee 2021년 6월 24일
Let's say I have an array. The difference between numbers is 1.
If I use a function 'diff' with 'unique', then I know whether the array is increasing or decreasing the constant amount.
ls = [1:10]'
unique(diff(ls))
%% ans = 1
In the above code, the answer is 1 obviously.
However, if I multiply 0.1 to the array, suddenly it does not work anymore.
I expected 'numel(unique(diff(ls * 0.1)))' gives '1' and the value is 0.1
However, Matlab says there are four different steps.
unique(diff(ls * 0.1))
%% ans =
% 0.1000
% 0.1000
% 0.1000
% 0.1000
I guess this is due to small precision. If I divide the array with a prime number then I understand the results. However, in this case, it is a very simple calculation, dividing by 10.
Why it happens? or how can I solve this problem?

채택된 답변

Matt J
Matt J 2021년 6월 24일
편집: Matt J 2021년 6월 24일
Use uniquetol(), e.g.,
ls=1:10;
uniquetol(diff(ls*0.1),1e-5)
ans = 0.1000
  댓글 수: 1
Sangmin Lee
Sangmin Lee 2021년 6월 24일
Thank you very much! I did not know there is this convienent function!

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

John D'Errico
John D'Errico 2021년 6월 24일
You do understand that MATLAB, as is true of almost any programming language, uses binary storage methods to store all floating point numbers. This is something you want, because it makes your computer really fast and efficient.
It also means, just as you cannot represent 1/3 exactly as a finite length decimal number, you cannot represent 1/10 as a finite length BINARY number.
If you tried that, it would look something like the infinitely repeating binary number:
0.00011001100110011001100110011001100110011001100110011010.....
where the ones represent negative powers of 2.
And that means you CANNOT expect MATLAB to get what you are trying to do right.
Instead, learn to use tolerances when you test for such tiny differences.

카테고리

Help CenterFile Exchange에서 Matrix Indexing에 대해 자세히 알아보기

제품


릴리스

R2019a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by