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
>>
  댓글 수: 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 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