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

8 次查看(过去 30 天)
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
>>

采纳的回答

Image Analyst
Image Analyst 2021-1-1
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:

更多回答(2 个)

Walter Roberson
Walter Roberson 2021-1-1
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 2021-1-1
Very interesting. In R2019b, I got
>> d = 163.0
d =
163
>> d == double(uint8(d))
ans =
logical
1
>> d == (uint8(d))
ans =
logical
1

类别

Help CenterFile Exchange 中查找有关 Numeric Types 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by