我试图对定点迭代进行编码以找到(x + 1)^(1/3)的解。我一直收到以下错误: 错误:' g'在第17行第6列附近未定义 错误:来自 第17栏第4行的固定点
clear -all;
clc;
function f = f(x)
f = (x+1)^(1/3)
f = g(x)
end
# Start out iteration loop
x1 = 0;
x2 = g(x1);
iterations = 0; # iteration counter
while abs(x2-x1 > 1e-5)
plot([x1 x1], [x1 g(x1)], 'k-')
plot([x1 x1], [x1 g(x1)], 'k--')
pause
x1 = x2;
x2 = g(x1);
iterations = iterations + 1;
end
iterations
x1
x2
我不知道出了什么问题。我的逻辑似乎是正确的。
答案 0 :(得分:1)
我稍微修改了您的代码,它可以获得f(x)=cos(x)-x
的解决方案,您可以将g(x)
更改为您想要的任何内容。
clear;
clc;
%# You function here
g=@(x) cos(x);
%# Start out iteration loop
x1 = 0;
x2 = g(x1);
iterations = 0;% # iteration counter
ezplot(g,[0,1]);
hold on
ezplot('x',[[0,1]])
while (abs(x2-x1) > 1e-5 && iterations<100)
plot([x1 x1], [x1 x2], 'k-')
plot([x1 x2], [x2 x2], 'k--')
%pause
iterations = iterations + 1;
x1 = x2;
x2 = g(x1);
end
iterations
[x1 x2]
解决方案将是:
iterations =
29
ans =
0.7391 0.7391
但是,你确定你的功能是对的吗?似乎此函数无法使用固定点迭代来解决,因为此处f(x)=0
等于g(x)=x
和g(x)=(x+1)^(1/3)+x
。但是如果我们用g(x)
(红色曲线)绘制h(x)=x
(蓝色曲线),我们有:
因此,如果我们从0开始,迭代无法收敛(x1
将显着增加,但根是-1
)。
希望它有所帮助!