# How to avoid effect of number of extra zeros after decimal point on the equality between two arrays?

2 views (last 30 days)
Omkar Chavan on 15 Aug 2020
Commented: Omkar Chavan on 16 Aug 2020
I have calculated two one diensonal matrices (i.e. two arrays) using two different equations. I am trying to check if corresponding values of both the arrays are equal or not. Following are the two methods that I followed to generate two arrays, namely y1 and y2,
Method: 1
R = 2.5;
x = (0:0.005:1);
y1 = R*x.*(1-x);
Method: 2
x = (0:0.005:1);
y2 = (-1*((x-0.5).^2) + 0.25)/0.4;
I am using following command to check equality between the values of two arrays,
y1 == y2
It is expected that both the arrays should be equal but, the output of above command is a logical array consisting of both zero's and one's. I tried manually cheking the values and they were equal. For example, (I have kept format of command window as long)
>> format long
>> y1(3)
ans =
0.024750000000000
>> y(3)
ans =
0.024750000000000
Later on, I tried this,
>> y1(3)==y(3)
ans =
logical
0
If I explicitely set these values to other variables,
>> format long
>> a=0.024750000000000;
>> b=0.024750000000000;
>> a==b
ans =
logical
1
In the question I am talking about number of extra zeros after decimal point because, if I explicitely remove those zeros from the values of both the arrays (by opening the arryas in variables window), I get,
>> format long
>> y1(3)
ans =
0.024750000000000
>> y(3)
ans =
0.024750000000000
>> y1(3)==y(3)
ans =
logical
1
What is happening here? What am I missing?
How do I check the equality between the two arrays generated in such a manner?
##### 2 CommentsShowHide 1 older comment
Omkar Chavan on 16 Aug 2020
Thank you very much for pointing that out for me.

Bruno Luong on 15 Aug 2020
"How do I check the equality between the two arrays generated in such a manner? "
tol = 2*eps(norm(y1,Inf));
norm(y1-y2,Inf)<=tol

Sara Boznik on 15 Aug 2020
Hi,
I also tried like you and also got wrong result. Later I checked for y1(201) where the ans=0 and I got correct result.
It is possible that is Matlab's bug.
Than I try also:
tf = isequal(y1,y2)
And also get logical 0.
But then I tried that:
y1 = struct('field1',0.005,'field2',2500);
y2 = struct('field2',2500,'field1',0.005);
tf = isequal(y1,y2)
And works, I got logical 1.
Best of luck.
##### 2 CommentsShowHide 1 older comment
Sara Boznik on 15 Aug 2020
Thank you so much.

R2020a

### Community Treasure Hunt

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

Start Hunting!