Double Conversion Matlab Conversion Error

Does anyone know why casting double() on the same floating point floating point number in Matlab (R2016a) changes the last digits? Here is an example:

 format 'long' x=3.2530601; %arbitrary single precision number x_s=single(x); x_d=double(x_s); 

If I look at the classes and values ​​of variables, I see the following: x and x_d are doubles, x_s is one, as expected. Values:

 x=3.253060100000000 x_s=3.2530601 x_d=3.253060102462769 

Since the number 3.2530601 can be represented as a double or single precision floating point number, I don’t understand why x and x_d do not match. They are farther than x+eps(x) . I thought that maybe Matlab is trying to work out double precision x_d using a rational approximation of fractions, but calling rat(x,16) does not give the same result as x_d . I am ignorant. Does anyone know what is going on here?

+5
source share
1 answer

There are two closely related questions ( Do MATLAB variables have REALLY double precision by default? And Why 24.0000, not equal to 24.0000 in MATLAB? ), Which you should know about, but this is not completely covered by any of them ...

When you calculate the decimal equivalent for a given significant and exponential floating point value, you can calculate it for as many decimal places you want, but any places outside the relative precision of the floating point end up having no real value and usually not even displayed. However, they seem to come into play here when converting a number with lower precision to a number with higher precision.

Look at your value for x_s , as it displays normally (only with significant digits) and how vpa will display it (with an arbitrary number of digits):

 >> x_s = single(3.2530601) % Create a single-precision number x_s = single 3.2530601 >> eps(x_s) % Floating-point relative accuracy ans = single 2.3841858e-07 >> vpa(x_s, 16) % Show 16 digits of precision, way more than the relative accuracy ans = 3.253060102462769 >> x_d = double(x_s) % Convert to double-precision x_d = 3.253060102462769 

Look at this! The numbers from vpa correspond to the numbers obtained when converting to double precision. It seems that when converting from single to double MATLAB calculates the decimal equivalent of a lower precision value in the number of digits for a higher precision value and uses this to initialize it.

+6
source

Source: https://habr.com/ru/post/1275484/


All Articles