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
Using symbolic math, you can get precise results:
x=sym('8.868')/sym('.1')
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With