Control separation accuracy

Consider the following simple division:

A=8.868; A/0.1 ans = 88.679999999999993 

This results in a small error due to floating point precision. Is there any way to prevent this? Basically, all I do is move the comma by one position, not being close to the maximum number of allowed digits in MATLAB.

I would like to get the result as:

 A/0.1 ans = 88.68 

where trailing zeros don't matter unless they are zero and don't contain some number on the 14th digit or so.

Interestingly, this problem also appears when rounding to N digits:

 R = (randi([8659 49847],[1e3 1]))/1e3; xmin = min(R); el = 0.1; step = 1/el; tmp1=xmin/el; tmp2=round(tmp1); tmp3=round(tmp2*el,3); tmp3 = 8.699999999999999 
+5
source share
4 answers

Using symbolic math, you can get accurate results:

 x=sym('8.868')/sym('.1') 
+6
source

You can always use a fixed point arithmetic where the slope is a multiple of 10. You will not have any inaccuracies when multiplying / dividing by ten. In Matlab, you can use a fixed-point panel

Edit: After your comment - it looks like you can set the slope to 0.05.

+5
source

This answer is posted for completeness only in my case.


I circumvented the issue somewhat in my case using the third unique output:

 el = 0.25; A = (randi([7364 84635],[1e4 1]))/1e3; B = A/el; C = round(B); D = C*el; [tmp1,tmp2,tmp3] = unique(D); E = tmp1(tmp3,:); all(E==D) ans = 1 

which performs binning correctly. Thus, although the center points may not be accurate with infinite accuracy, they contain at least 10 digits, which is more than the three-digit accuracy of my source data.

+4
source

You can represent your numbers as integers. As long as you do not convert to float, you do not lose accuracy:

 A = 8.868; div = 0.1; [N1,D1] = rat(A); [N2,D2] = rat(div); % divide A by div: N = N1 * D2; D = N2 * D1; 

Of course, your numbers may be inaccurate, as indicated in other answers / comments. Converting to fractions can also introduce an approximation, but it depends on the number you're dealing with and the tol parameter to rat .

+3
source

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


All Articles