我正在尝试为代码添加边界,但是在找出放置它们的位置时遇到了麻烦。等式变为:f(x)= e ^(6x)+ 1.441e ^(2x)-2.079e ^(4x)-0.333 = 0,-1> = x <= 0
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 :(得分:0)
我会在Newton步骤之后添加检查。这不会防止某人输入-1或1作为初始猜测,但这可以在您进行输入验证时完成。我接受了Ander Biguri的建议并将c
更改为x
:
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.113210
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