How do I avoid cancellation errors due to floating point representation in my program in MATLAB?

I have written code wherein I lose significant digits in variables when I perform subtraction operations. I want to be able to perform these operations keeping high precision in the variables, so that I can avoid the cancellation error.

 Accepted Answer

The use of symbolic objects from the Symbolic Math Toolbox can help to avoid cancellation errors that are caused due to loss of significant digits. The following code example shows how to achieve this.
Original code:
n=53;
h = 2^(-n);
g = (sin(1+h) - sin(1))/h;
'g' goes to zero since the numerator goes to zero
To work around this, use VPA:
n=53;
h = vpa(2^(-n));
g = (vpa(sin(1+h)) - vpa(sin(1)))/h;
'g' turns out to be around 0.5563 which is the desired value.
Please note that this method involves the creation of Symbolic objects 'h' and 'g', which consume an amount of memory which is proportional to the number of digits of precision stored in them.

More Answers (0)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!