Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Controlling division precision

Consider the following simple division:

A=8.868;
A/0.1
ans =
  88.679999999999993

This results in a small mistake, due to floating point precision. Is there any way to prevent this from happening? Basically all I'm doing is shifting the comma one position, whilst not being close to the maximum number of allowable digits in MATLAB.

I would like to obtain a result as:

A/0.1
ans =
  88.68

where trailing zeros are of no concern, as long as they are zero only, and not contain some number at the 14th digit or so.

Interestingly this issue also pops up 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
like image 800
Adriaan Avatar asked Nov 17 '15 10:11

Adriaan


3 Answers

Using symbolic math, you can get precise results:

x=sym('8.868')/sym('.1')
like image 90
Daniel Avatar answered Oct 23 '22 11:10

Daniel


You can always use fixed point arithmetics where the slope is a multiple of 10. You won't have any inaccuracies when you multiply/divide by ten. In Matlab, you can use Fixed Point Toolbox

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

like image 35
Andrey Rubshtein Avatar answered Oct 23 '22 12:10

Andrey Rubshtein


This answer is only posted for completeness in my case.


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

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 does the binning correctly. So even though the centre points might not be exact with infinite precision, they are within at least some 10 digits, which is more than the 3 digit precision of my original data.

like image 4
Adriaan Avatar answered Oct 23 '22 12:10

Adriaan