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

1 次查看(过去 30 天)
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 个)

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 中查找有关 Logical 的更多信息

产品


版本

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by