sum() missing for certain values

12 次查看(过去 30 天)
Hello,
I have an issue which i do not understand using the basic function sum(). I have an array with 2 million values consisting of doubles from 0 to 1 with 3 decimals (rounded). I want to display the distribution by counting every possible output except zero and one using the sum function (0.001-0.999). I tried to calculate it with and without a loop but im allways missing the sum for certain values either way. Example code below.
Vector=rand(2000000,1);
Vector=round(Vector,3,"decimals");
numbers=0.001:0.001:0.999;
b=1;
distribution2=double.empty(999,0);
for x=0.001:0.001:0.999
distribution2(b)=sum(Vector==x);
b=b+1;
end
figure()
plot(numbers,distribution2)
title('distribution2 (with loop)')
distribution(:)=sum(Vector==numbers);
figure()
plot(numbers,distribution)
title('distribution')
As u can see I get a feedback with different gaps using the calculation methods as shown above. I checked the gaps (e.g. 0.7) by using the sum function inside the command window and got back a positive feedback
>> sum(Vector==0.7)
ans =
2009
Can someone explain to me why I am having issues calculating the sum for all numbers and why I am getting two different results depending on how I am trying to calculate it?
Thank you and nice Regards
Anton
  4 个评论
Stephen23
Stephen23 2023-2-20
编辑:Stephen23 2023-2-20
"I'm aware that matlab is not able to display exactly 0.7 due to binary flaoting numbers"
MATLAB certainly can "display exactly 0.7", even binary floating point. Lets try it right now:
format short G
0.7
ans =
0.7
"i was not aware that matlab is using different construction for 0.7 inside command window and inside code"
I have never heard that MATLAB uses a "different construction for 0.7 inside command window and inside code", and I strongly doubt that such a "different construction" exists due solely to where the value is defined. I tried it in R2018a:
The two values are exactly the same.
The links I posted earlier introduce floating point number behavior. David Goldberg's article is highly recommended.
Anton
Anton 2023-2-21
Thank you for clarificaton. I'll read the article.

请先登录,再进行评论。

采纳的回答

KSSV
KSSV 2023-2-20
Don't use
sum(Vector==x)
use
tol = 0.0001 ; % set your acceptable tolerance
sum(abs(Vector-x)<tol) ;

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

产品


版本

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by