這是我的MATLAB代碼。函數trapezoidal()是單獨定義的,並且工作正常。錯誤使用==> fprintf函數沒有爲'sym'輸入定義
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);
'trapezoidal'返回什麼數據類型? – 2014-09-11 09:27:20
梯形函數返回一個浮點數。 – Ruwangi 2014-09-11 09:33:28
你可以發佈該功能嗎? – 2014-09-11 09:38:43