我看不到牛顿方法的Matlab代码输出,我缺少什么?

时间:2019-08-28 19:02:31

标签: matlab numerical-methods nonlinear-functions newtons-method

因此,我有以下Matlab代码,其中我试图计算Newton's Method来解决非线性方程式(特别是确定平方根)。我看不到我的两个fprintf()语句的输出,所以我认为我从根本上误解了MATLAB调用函数的方式。

我觉得这里有一些根本性的东西,我在这里不见了。

我正在Matlab Web应用程序https://matlab.mathworks.com/上运行它

我的代码如下:

clear all
p = 81; %set to whatever value whose square root you want to find.
egFun = @ (x) x^2 - p;
egFunDer = @ (x) 2*x;
firstGuess = p;
Err = 0.00001;
imax = 20;

%% (+) function, functionDervivate, X-estimate, Error, i-Maximum (-) X-Solution
function Xsolution = NewtonRoot(Fun, FunDer, Xest, Err, imax)
    for i = 1 : imax
        fprintf("test %f", i)
        % below is the newton's method formula in action
        Xi = Xest - Fun(Xest)/FunDer(Xest)
        % let Xest be replaced with our new value for X so that we can
        % perform the next iteration
        if(abs(0-Fun(Xi)) <= Err)
            Xsolution = Xi;
            break
        end
        Xest = Xi
    end
    Xsolution = Xi;
end
%%
function answer = main
    answer = NewtonRoot(egFun, egFunDer, firstGuess, Err, imax)
    fprintf("the Solution is %f", answer)
end

我希望看到一个答案值,该值应该打印到控制台上,以及我为调试而输入的两个fprintf()语句。

1 个答案:

答案 0 :(得分:2)

您需要在主代码中调用NewtonRoot函数。

clear all
p = 81; %set to whatever value whose square root you want to find.
egFun = @ (x) x^2 - p;
egFunDer = @ (x) 2*x;
firstGuess = p;
Err = 0.00001;
imax = 20;
%% 
answer = NewtonRoot(egFun, egFunDer, firstGuess, Err, imax)
fprintf("the Solution is %f", answer)

%% (+) function, functionDervivate, X-estimate, Error, i-Maximum (-) X-Solution
function Xsolution = NewtonRoot(Fun, FunDer, Xest, Err, imax)
    for i = 1 : imax
        fprintf("test %f", i)
        % below is the newton's method formula in action
        Xi = Xest - Fun(Xest)/FunDer(Xest)
        % let Xest be replaced with our new value for X so that we can
        % perform the next iteration
        if(abs(0-Fun(Xi)) <= Err)
            Xsolution = Xi;
            break
        end
        Xest = Xi
    end
    Xsolution = Xi;
end