0

In this Matlab code, I'm trying to generate a random vector of int and dividing with their sum to make it behave like probability values. But sometimes(not always) its not summing upto 1. Is it a floating point precision issue ?? How can I fix it ?

for I = 1:5
A = randi([1,10],[1,10]);
% Just get a 10 length vector of random int
A = A/sum(A);
% Make the vector normalize to
% behave like probability values
   if sum(A)~=1
       % should sum to one
       % but sometimes its not
       disp(['Not equal to 1', sum(A)]);
   else
       disp('Equal to 1');
   end
end
ayandas
  • 2,070
  • 1
  • 13
  • 26
  • 2
    Yup, floating point precision issue. Even when you normalize to ensure the sum is 1, you are checking to see if a floating-point sum is **exactly** equal to 1 and most of the time it won't. Please see the duplicate on an explanation as to why this is the case and methods for addressing this issue. – rayryeng Jan 07 '16 at 15:51
  • Thanks for pointing out @rayryeng – ayandas Jan 07 '16 at 16:03

0 Answers0