Why assignment changes the precision of calculation of MATLAB?

74 views Asked by At

I am writing some scripts using MATLAB R2020a and I am having a problem: there are two values I want to assign to a vector z_samples, namely x_samples(l_indexes)./sum(x_samples)(a vector) and x_samples(T_deno_index)./sum(x_samples) - 1(a value) and they have a sum of 0 (here x_samples is a Gaussian vector from the function mvnrnd and l_indexes is an index vector which doesn't overlap the index T_deno_index. l_indexes and T_deno_index together cover all the elements in x_samples):

sum(x_samples(l_indexes)./sum(x_samples)) + x_samples(T_deno_index)./sum(x_samples) - 1 = 0

picture: sum to zero

however, when I assign them separately to the z_samples:

z_samples(l_indexes) = x_samples(l_indexes)./sum(x_samples);
z_samples(T_deno_index) = x_samples(T_deno_index)./sum(x_samples) - 1;

the sum of z_samples is not 0:

>> sum(z_samples) 

ans = 
    
    -5.5511e-17

I want to know what is going on here and how can I fix this.

Any comments are appreciated.

0

There are 0 answers