MATLAB Answers

What is the difference between Double 1.0000 and Double 1 ?

4 views (last 30 days)
Rahim Rahim
Rahim Rahim on 29 Nov 2020
Edited: John D'Errico on 29 Nov 2020
When I test;
A=1;
B=1.000;
if (A==B)
"True"
else
"false"
end
The results is always False and the type of A and B, the both are Double.
I want the results of the both variable becomes True;

  0 Comments

Sign in to comment.

Answers (2)

Walter Roberson
Walter Roberson on 29 Nov 2020
A=1;
B=1.000;
if (A==B)
"True"
else
"false"
end
ans = "True"
When you see something displaying as 1 with no decimal points, then if you are using the default display routines, that means that the value is exactly 1.
When you see something displaying as 1.0 with several 0s after it, then if you are using the default display routines, that meanst that the value is not exactly 1, but that it has been rounded to 1 for display purposes.
You should try
format long g
B
B-A

John D'Errico
John D'Errico on 29 Nov 2020
Edited: John D'Errico on 29 Nov 2020
If you see the number in MATLAB displayyed as 1.000 in the command window, then almost always you don't have the number 1. Instead, it LOOKS like 1, but has been rounded to that value for display purposes.
format short
x = [1, 1.000001 0.999999]
x = 1×3
1.0000 1.0000 1.0000
Are they all 1? Exactly? No. In fact, the last two have been rounded to 1. I told MATLAB to display only a few digits. And since that is the default, it is what most people seem to use. And even though the first element of that vector is indeed exactly 1, MATLAB still shows the zeros.
x == 1
ans = 1x3 logical array
1 0 0
MATLAB does clearly know that one of them is exactly 1, as you can see. And if I show only that first element, MATLAB tries to display the number as 1, as opposed to 1 with some zeros appended.
x(1)
ans = 1
x(2)
ans = 1.0000
For x(2) it still needs to round off, so it displays those spare zeros. Of course, we can change the default format to not round to only a few digits. Now we will see longer versions those numbers, and now we might realize that only the first element exactly 1.
format long g
x
x = 1×3
1 1.000001 0.999999
Remember this clue in MATLAB: If a number shows extra zeros beyond the end of the non-zero digits, that number probably is not stored exactly as what you see.
format short
y = 0.95
y = 0.9500
But since 0.95 is not representable exactly in binary, 0.95 is stored as more like the number:
sprintf('%0.17f',y)
ans = '0.94999999999999996'

  0 Comments

Sign in to comment.

Products


Release

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by