【问题标题】:Why is Matlab rounding off to 4 places after decimal?为什么matlab四舍五入到小数点后4位?
【发布时间】:2014-06-03 13:04:00
【问题描述】:

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

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 终端告诉我格式设置为长。我不知道为什么会发生这种情况。

这是表格的样子:

#   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.17545990358921 0.17477436859764 0.00068553499157。您是否尝试重新启动 Matlab?

标签: matlab truncation taylor-series


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多