以下是一个可能的MATLAB函数实现:

function [polynomial] = interpolation(x, y, method) % x: 数据向量 % y: 数据向量 % method: '待定系数'、'拉格朗日'或'牛顿' % polynomial: 适当形式的插值多项式

% 异常处理 if length(x) ~= length(y) error('x和y的长度必须相等'); end if ~ismember(method, {'待定系数', '拉格朗日', '牛顿'}) error('不支持的插值方法'); end

% 待定系数 if strcmp(method, '待定系数') V = vander(x); coefficients = V \ y'; polynomial = poly2str(flip(coefficients)'); end

% 拉格朗日 if strcmp(method, '拉格朗日') n = length(x); polynomial = ''; for i = 1:n numerator = poly2str(y(i)); denominator = '1'; for j = 1:n if i ~= j numerator = [numerator '(x-' num2str(x(j)) ')']; denominator = [denominator '(x-' num2str(x(j)) ')']; end end term = [numerator '/' denominator '+']; polynomial = [polynomial term]; end polynomial(end) = ''; % 去掉最后一个加号 end

% 牛顿 if strcmp(method, '牛顿') n = length(x); divided_differences = zeros(n); divided_differences(:, 1) = y'; for j = 2:n for i = j:n divided_differences(i, j) = (divided_differences(i, j-1) - divided_differences(i-1, j-1)) / (x(i) - x(i-j+1)); end end coefficients = divided_differences(n, :); polynomial = poly2str(flip(coefficients)); end

% 辅助函数 function [str] = poly2str(coefficients) n = length(coefficients) - 1; str = ''; for i = n:-1:2 if coefficients(i) ~= 0 if coefficients(i) == 1 term = 'x^' num2str(i-1); elseif coefficients(i) == -1 term = '-x^' num2str(i-1); else term = [num2str(coefficients(i)) '*x^' num2str(i-1)]; end str = [str term '+']; end end if coefficients(1) ~= 0 str = [str num2str(coefficients(1))]; end

% 比较三种方法在人工数据上的性能 x = 0:0.1:1; y = sin(x); methods = {'待定系数', '拉格朗日', '牛顿'}; for i = 1:length(methods) tic; interpolation(x, y, methods{i}); time = toc; disp([methods{i} '插值的时间:' num2str(time) '秒']); end

% 使用动力学模型表明牛顿插值优于拉格朗日插值 x = 0:0.1:1; y = sin(x); n = length(x); x_test = 0:0.01:1; y_true = sin(x_test); y_lagrange = zeros(size(x_test)); y_newton = zeros(size(x_test)); for i = 1:length(x_test) % 拉格朗日 numerator = 0; denominator = 0; for j = 1:n product = y(j); for k = 1:n if k ~= j product = product * (x_test(i) - x(k)) / (x(j) - x(k)); end end numerator = numerator + product; denominator = denominator + 1 / (x_test(i) - x(j)); end y_lagrange(i) = numerator / denominator; % 牛顿 divided_differences = zeros(n); divided_differences(:, 1) = y'; for j = 2:n for k = j:n divided_differences(k, j) = (divided_differences(k, j-1) - divided_differences(k-1, j-1)) / (x(k) - x(k-j+1)); end end coefficients = divided_differences(:, end); polynomial = poly2sym(flip(coefficients)); y_newton(i) = subs(polynomial, x_test(i)); end error_lagrange = norm(y_lagrange - y_true); error_newton = norm(y_newton - y_true); disp(['拉格朗日插值的误差:' num2str(error_lagrange)]); disp(['牛顿插值的误差:' num2str(error_newton)]);

en


原文地址: https://www.cveoy.top/t/topic/c0z8 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录