为什么Matlab四舍五入到4位?

时间:2014-04-18 23:33:47

标签: matlab truncation taylor-series

我有以下代码打印/绘制出泰勒级数近似的结果。

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)');

但是,打印出来的表由于某种原因在小数点后截断4位。打字:

get(0,'format')

进入Matlab终端告诉我格式设置为long。我不知道为什么会发生这种情况。

这就是表格的样子:

#   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

这种舍入似乎只发生在符号函数上。当不使用它时确实会发生。知道为什么以及如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

我可以重现您的输出设置digits(4)。将它设置回32,一切都应该没问题。

digits函数允许设置mupad变量精度算术的精度。由于某种原因,精度降低到4位。