MATLAB 牛顿迭代法求平方根算法实现
function [x, iter] = newton_sqrt(a, x0, tol, max_iter) % a: 待求平方根的数 % x0: 初值 % tol: 容差 % max_iter: 最大迭代次数
% 初始化迭代次数 iter = 0;
% 进行牛顿迭代 while iter < max_iter % 计算新的迭代值 x = (x0 + a/x0)/2; % 判断是否满足容差要求 if abs(x - x0) < tol return; end % 更新迭代次数和迭代值 iter = iter + 1; x0 = x; end
% 若迭代次数超过最大迭代次数仍未满足容差要求,则输出警告信息 warning('The iteration has not converged to the desired tolerance within the maximum number of iterations.');
原文地址: https://www.cveoy.top/t/topic/jEVe 著作权归作者所有。请勿转载和采集!