你如何计算任何值的倒数?

时间:2017-03-30 20:26:49

标签: matlab

我正在尝试计算任何值的倒数。这就是我提出的问题,但是我被困住了。

function xnext = newtondivide(xnext, xprev, tol)

its = 0;
while(abs(xnext-xprev)>tol && its < maxit)    
    xnext = xprev(2-a*xprev);% I am confused here because I don't know what a is.
    its = its + 1;
end 
its
return 

1 个答案:

答案 0 :(得分:0)

a是您尝试查找的倒数的输入值。

问题指出你的函数应该有2个参数,所以另一个必须是&#34;用户提供的容差&#34;。

以下代码不是一个有效的答案。 因为这显然是一本教科书练习,我不打算为你写一个完整的脚本,这不是StackOverflow的用途。但是,作为一个学习点,我重新组织了您的功能,以便通过我推荐的更改,它可以正常工作。

阅读建议更改的注释,通常用*???*表示。

function x = newtondivide(a, tol)
% You must input a, since that's the thing you want to find the reciprocal of...
    x0 = 1e-6; % This is specified in the question

    xnext = x0; 
    % Initialise xprev to something where xnext - xprev >= tol, otherwise you will never enter the while loop
    % xprev = *???*; 
    its = 0;
    % You haven't yet defined maxit, but you are about to test against it! 
    % maxit = *???*
    while abs(xnext-xprev) >= tol && its < maxit    
        % You must update the value of xprev, currently it never changes!
        %
        % xprev = *???*
        %
        % You missed the * before the bracket - Matlab doesn't do implicit multiplication
        xnext = xprev*(2-a*xprev); 
        its = its + 1;
    end 

    x = xnext; % This will get returned, as the first line specifies x should be returned   
end