0

我试图给代码添加边界,但有困扰搞清楚把它们放在哪里。该方程变为:F(X)= E ^(6×)+ 1.441e ^(2×) - 2.079e ^(4×) - 0.333 = 0,-1> = X < = 0将代码添加到代码中,matlab

function c = newton(x0, delta) 

c = x0;  
fc = f(x0);     
fprintf('initial guess: c=%d, fc=%d\n',c,fc) 

if abs(fc) <= delta    % check to see if initial guess satisfies 
     return;      % convergence criterion. 
end; 

while abs(fc) > delta, 
    fpc = fprime(c);   

    if fpc==0,     % if fprime is 0, abort. 
    error('fprime is 0')  % the error function prints message and exits 
    end; 

    c = c - fc/fpc;    % Newton step 
    fc = f(c); 
    fprintf(' c=%d, fc=%d\n',c,fc) 
end; 

function fx = f(x) 
    fx = exp(6*x)+1.441*exp(2*x)-2.079*exp(4*x)-0.333;   % Enter your function here. 
    return; 
function fprimex = fprime(x) 
    fprimex = 6*exp(6*x)+6*exp(2*x)*(ln(2))^2-4*exp(4*x)*ln(8); % Enter the derivative of function 

    return; 
+0

如果你改变了变量名'C'到'x',它可能是更容易你明白了! –

回答

0

我会牛顿步骤后添加检查。这不会防止某人输入-1或1作为初始猜测,但是当您进行输入验证时可以完成此操作。我把安德Biguri的建议,改变了cx

function x = newton(x0, delta) 
    x = x0;  
    fx = f(x0);     
    fprintf('initial guess: x=%f, fx=%f\n',x,fx) 

    if abs(fx) <= delta    % check to see if initial guess satisfies 
     return;      % convergence criterion. 
    end; 

    while abs(fx) > delta, 
    fpx = fprime(x); 

    if fpx==0,     % if fprime is 0, abort. 
     error('fprime is 0')  % the error function prints message and exits 
    end; 

    x = x - fx/fpx;    % Newton step 
    if(x > 1 || x < -1) 
     error('x out of bounds!'); 
    end 

    fx = f(x); 
    fprintf(' x=%f, fx=%f\n',x,fx) 
    end 
end 

function fx = f(x) 
    fx = exp(6*x)+1.441*exp(2*x)-2.079*exp(4*x)-0.333;   % Enter your function here. 
end 

function fprimex = fprime(x) 
    fprimex = 6*exp(6*x)+6*exp(2*x)*(log(2))^2-4*exp(4*x)*log(8); % Enter the derivative of function 
end 

这里的输出我得到:

>> x = newton(0.5, 0.5*1e-4) 
initial guess: x=0.500000, fx=8.307733 
    x=0.375798, fx=2.908518 
    x=0.263566, fx=1.003444 
    x=0.165026, fx=0.340291 
    x=0.081315, fx=0.
    x=0.012704, fx=0.036909 
    x=-0.041514, fx=0.011793 
    x=-0.082894, fx=0.003695 
    x=-0.113515, fx=0.001136 
    x=-0.135581, fx=0.000341 
    x=-0.151084, fx=0.000098 
    x=-0.161526, fx=0.000025 

x = 

    -0.1615 
+1

Ander的建议:P干得好。 –

+0

谢谢!你在命令窗口中输入什么来获取输出,由于某种原因,当我插入initila点和什么,我不断收到错误。也许我输错了。 –

+0

没关系,愚蠢的错误....感谢球员的帮助! –