How can I convert a double variable to uint8 and convert it back to double?

22 views (last 30 days)
I'm doing some simple image processing stuff and during it I faced with a strage problem.
The problem is: 163 is not equal to 163.0000! and I don't know why it happens and how I should fix it.
look at below code to make it more clear:
>> u = W_image(1); d = de(1);
>> d
d =
163.0000
>> u
u =
uint8
163
>> d == u
ans =
logical
0
>> d == double(u)
ans =
logical
0
>> d == cast(u, 'double')
ans =
logical
0
>>
NOTE: W_image and de are two identical matrix just with different types!
My Question: What functions should I use to see result 1 in below code?
>> d == double(uint8(d))
ans =
logical
0
>>
  1 Comment
Ive J
Ive J on 1 Jan 2021
Edited: Ive J on 1 Jan 2021
Maybe you just need to round(d), because I guess even you try
d == 163
You'll get false!

Sign in to comment.

Accepted Answer

Image Analyst
Image Analyst on 1 Jan 2021
d is not 163. It probably has some digit way out in the 7th or 8th decimal place. If you want a perfect integer, just round it
fprintf('d really equals 0.20f\n', d);
d = round(d);
See the FAQ:

More Answers (2)

Walter Roberson
Walter Roberson on 1 Jan 2021
NOTE: W_image and de are two identical matrix just with different types!
No they are not.
You are using format short ,which has the property that values which are exact integers are displayed without decimal points. d is not exactly 163
Use
format long g
d - 163
to see the difference.
Any time that you have values computed different ways, they will not necessarily be equal. For example 29/7*7-29 = 3.5527136788005e-15

J Chen
J Chen on 1 Jan 2021
Very interesting. In R2019b, I got
>> d = 163.0
d =
163
>> d == double(uint8(d))
ans =
logical
1
>> d == (uint8(d))
ans =
logical
1

Community Treasure Hunt

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

Start Hunting!