这是我的MATLAB代码。函数trapezoidal()是单独定义的,它可以正常工作。
syms x;
f = 10 + 2 * x - 6 * (x^2) + 5 * (x^4);
a = 0;
b = 2;
ans_3points = trapezoidal(f, a, b, 3);
ans_5points = trapezoidal(f, a, b, 5);
ans_7points = trapezoidal(f, a, b, 7);
fprintf('Integral estimate for three equally spaced points is %f.\n', ans_3points);
fprintf('Integral estimate for five equally spaced points is %f.\n', ans_5points);
fprintf('Integral estimate for seven equally spaced points is %f.\n', ans_7points);
actual_ans = int(f, 0, 2);
error_3points = 100 * (actual_ans - ans_3points) / actual_ans;
error_5points = 100 * (actual_ans - ans_5points) / actual_ans;
error_7points = 100 * (actual_ans - ans_7points) / actual_ans;
fprintf('Percentage relative error for three equally spaced points is %f.\n', error_3points);
fprintf('Percentage relative error for five equally spaced points is %f.\n', error_5points);
fprintf('Percentage relative error for seven equally spaced points is %f.\n', error_7points);
但是这会在打印error_3points的行中出现以下错误: ???使用==>时出错fprintf中 没有为'sym'输入定义函数。
我没有在fprintf()中输入任何'sym'输入吗? ans_3points,ans_5points,ans_7points打印没有任何问题。 计算错误但我检查时它们显示为分数。 这段代码究竟出现了什么问题?我真的无法弄明白。 谢谢。
功能trapezoidal
:
function l = trapezoidal(f, a, b, n)
N = n - 1; % N - the number of segmets
syms x;
series_sum = 0;
for i = (0 : (N - 1))
series_sum = series_sum + subs(f, x, xterm(i, a, b, n)) + subs(f, x, xterm((i + 1), a, b, n));
end
l = series_sum * (b - a) / (2 * N);
答案 0 :(得分:3)
问题在于使用函数int
actual_ans = int(f, 0, 2);
`actual_ans'仍然是一个象征性的变量,即使它是一个常数。您可以使用
将其转换为数字变量actual_ans = double(actual_ans);