I have the following code that prints/graphs out the result of a Taylor Series Approximation.
close all;
clear;
clc;
fprintf('#\tf(pi/3)\t\t\t\tfn(pi/3)\t\t\tEt\n');
% actual function
syms x;
f(x)=exp(-x)*cos(x);
h = ezplot(f);
grid on;
hold on;
set(h,'Color','b', 'LineWidth', 3);
% presets for Taylor.
a=1;
maxorder=10;
% Taylor Series
y(x)=f(a);
for n=1:maxorder
d(x) = diff(f(x),x,n);
y(x) = y(x) + d(a)*((x-a)^n)/factorial(n);
error=double(f(pi/3))-double(y(pi/3));
fprintf('%.0f\t%.14f\t%.14f\t%.14f\n',n,double(f(pi/3)),double(y(pi/3)),error);
end
h = ezplot(y);
axis([0, 4.5,-1, 1]);
set(h,'Color','r', 'LineWidth', 3);
set(gca,'FontSize', 15');
title('Taylor Series of e^{-x}cos(x)');
However, the table that gets printed out is for some reason getting truncated 4 places after the decimal point. Typing:
get(0,'format')
into the Matlab terminal tells me the formatting is set to long. I have no clue why this could be happening.
This is what the table looks like:
# f(pi/3) fn(pi/3) Et
1 0.17550000000000 0.17480000000000 0.00070000000000
2 0.17550000000000 0.17550000000000 0.00000000000000
3 0.17550000000000 0.17550000000000 0.00000000000000
4 0.17550000000000 0.17550000000000 0.00000000000000
5 0.17550000000000 0.17550000000000 0.00000000000000
6 0.17550000000000 0.17550000000000 0.00000000000000
7 0.17550000000000 0.17550000000000 0.00000000000000
8 0.17550000000000 0.17550000000000 0.00000000000000
9 0.17550000000000 0.17550000000000 0.00000000000000
10 0.17550000000000 0.17550000000000 0.00000000000000
This rounding seem to happen only with symbolic functions. It does happen when those are not used. Any idea why and how I can fix that?
I can reproduce your output setting digits(4)
. Set it back to 32 and everything should be okay.
The digits
functions allows to set the precision of mupad variable precision arithmetic. The precision was reduced to 4 digits for some reason.