When I compute the following in Matlab
myeps = abs(3*(4/3-1)-1);
format long e
eps_myeps = [eps ; myeps]
The output is as follows:
eps_myeps =
2.220446049250313e-16
2.220446049250313e-16
Why is myeps
not 0? Why does this not hold when the base is 3 instead of 2?
CodePudding user response:
Code 4/3
is 4/3 in math. 4/3 is not exactly encodable as a floating point number. Most floating point numbers are dyadic rationals (an integer times some power of 2) and a nearby value is used.*1 Much like we can not write 4/3 exactly in decimal, only 1.3333333 and stop after so many digits.
In this case, The subtraction is expected to be exact as well as the multiplication and final subtraction. Yet the first quotient is not 4/3 and so the final result might not be 0.0.
*1
decimal 1.3333333333333332593184650249895639717578887939453125
hex 0x1.5555555555555
CodePudding user response:
I feel the OP is also searching for an answer for "How could obtain a 0 as an answer", besides "Why is myeps not 0". So here is the answer. You'll need the Symbolic Math Toolbox for MATLAB.
You can create symbolic numbers by using sym. Symbolic numbers are exact representations, unlike floating-point numbers.
So if you type 3*(sym(4)/sym(3)-1)-1
into MATLAB (once you got the toolbox), the answer will be exact
0
Just mind the sym(4)/sym(3)
part. If you try sym(4/3)
, MATLAB will get a floating-point first, then try to convert it to symbolic. That will lose precision and not produce 0 as an answer.