我正在尝试使用最小化来计算多项式的系数p(x) = 1 + c(1)x + c(2)x^2
以近似e^x
. 我需要在xi = 1 + i/n
自然数i
上使用点[1,n]
,首先是n=5
,然后n=10
等。方法是最小化1
,2
和inf norm(p(x) - e^x)
使用fminsearch。所以输出应该是 3 的 2 个系数p(x)
。任何建议表示赞赏。
问问题
589 次
1 回答
0
好吧,如果有人想知道,我终于弄清楚了这个问题。
for l = [1 2 inf]
fprintf('For norm %d\n', l)
fprintf('Coefficients c1 c2\n')
for n = [5 10 100]
i = 1:n ;
x = 1 + i/n ;
c = [1 1] ;
%Difference function that we want to minimize
g = @(c) x.*c(1) + x.^2.*c(2) + 1 - exp(x);
f_norm = @(c) norm(g(c), l) ;
C = fminsearch(f_norm, c);
fprintf('n = %d ', n)
fprintf('%f %f\n', C(1), C(2))
% Compare plot of e^x and p(x).
p = @(x) C(1)*x + C(2)*x.^2 + 1;
xx = linspace(1,2,1e5);
figure;
plot(xx, p(xx), '--r', xx, exp(xx));
str = sprintf('Plot with n = %d, for norm %d', n,l);
title(str,'FontSize',24)
xlabel('x','FontSize',20)
ylabel('y','FontSize',20)
legend('p2 approximation','exponential');
end
end
这最终回答了这个问题。
于 2014-11-03T18:57:28.443 回答