This is an iterative program, but the result is wrong. Why?

1 visualización (últimos 30 días)
希媛
希媛 el 18 de Mzo. de 2024
Editada: VBBV el 19 de Mzo. de 2024
这是一个迭代法的程序,但结果是错误的,这是为什么呢?
  2 comentarios
Steven Lord
Steven Lord el 18 de Mzo. de 2024
What purpose do the sign calls in your code serve?
VBBV
VBBV el 19 de Mzo. de 2024
Editada: VBBV el 19 de Mzo. de 2024
Hi @希媛 the comparison of output values from the function based on some inputs is not a correct way to test the program correctness since sin & cos functions exhibit sign changes according to different values of inputs
g = @(x) cos(x);
p = 20; % initial value
xc = fpi(g,p,1e-6)
xc = 0.9179
cos(g(p))
ans = 0.9179
function xc = fpi(g,x0,tol)
x(1) = g(x0); % <<<
x(2) = g(x(1));
i = 1;
while abs(sign(i+1)-sign(x(i))) > tol
x(i+2) = g(x(i+1));
i=i+1;
end
xc = x(end);
end

Iniciar sesión para comentar.

Respuestas (1)

Torsten
Torsten el 18 de Mzo. de 2024
Editada: Torsten el 18 de Mzo. de 2024
g = @(x) cos(x);
xc = fpi(g,1,1e-6)
xc = 0.7391
g(xc)
ans = 0.7391
function xc = fpi(g,x0,tol)
xold = x0;
error = 2*tol;
while error > tol
x = g(xold);
error = abs(x-xold);
xold = x;
end
xc = x;
end

Etiquetas

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by