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

8 ビュー (過去 30 日間)
VILMIL
VILMIL 2021 年 1 月 1 日
回答済み: J Chen 2021 年 1 月 1 日
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 件のコメント
Ive J
Ive J 2021 年 1 月 1 日
編集済み: Ive J 2021 年 1 月 1 日
Maybe you just need to round(d), because I guess even you try
d == 163
You'll get false!

サインインしてコメントする。

採用された回答

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 Center および File ExchangeNumeric Types についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by