matlab - 使用 False Position Method 计算 matlab 问题中的绝对和相对误差
问题描述
我f = @(x) 2*sin(x) - exp(x)/4-1
在我的错误位置算法中使用该函数。假定根-5.7591
是正确的根。但是,在我的算法中计算误差的不同方法是不正确的。如果没有计数器来停止 while 循环,那么只要我使用绝对近似值(标志 = 1)或相对误差(标志 = 2),它就会永远持续下去。
flag = 1 means calculate using absolute approx error
flag = 2 means calculate using absolute relative error
flag = 3 means calculate using true error (this one works fine)
使用的范围是 [-7,-5] 并且当误差低于 10^6 时循环应该停止
下面是代码及其下面的输入和输出:
function [root,counter] = FalsePosition(f,x1,x2,d,flag)
sx1 = x1;
sx2 = x2;
if(f(x1)*f(x2) >= 0)
disp("x1 and x2 are not correct")
return
end
while(flag > 3 || flag < 1)
flag = input("Flag used incorrectly! please enter a value 1 - 3: ");
end
i = 0;
E = d;
while(i < 100 && E >= d)
x3 = x2 - f(x2)*(x2-x1)/(f(x2)-f(x1));
i = i + 1;
if(f(x1)*f(x3) < 0)
x2 = x3;
x = x1;
else
x1 = x3;
x = x2;
end
if(flag == 1)
E = abs(x - x3); % abs approx error
elseif(flag == 2)
e = abs(x - x3);
E = e/abs(x3); % abs relative error
else
E = abs(f(x3)); % true error
end
end
counter = i;
root = x3;
if(flag == 1)
method = "Absolute approximate error";
elseif(flag == 2)
method = "Absolute relative approximate error";
else
method = "True absolute error";
end
disp("Method used: " + method);
disp("Brackets: " + sx1 + " and " + sx2);
disp("The root is " + root);
disp("Iterations: " + counter);
disp(" ");
输入输出:
>> f = @(x) 2*sin(x) - exp(x)/4-1;
>> [v,c] = FalsePosition(f,-7,-5,10^-6,2)
Method used: Absolute relative approximate error
Brackets: -7 and -5
The root is -5.7591
Iterations: 100
v =
-5.7591
c =
100
其中 v 是根,c 是 while 循环的迭代次数
解决方案
我意识到错误位置方法(以及正割方法)对系统中的初始括号非常敏感。在我的示例中,我使用了引起问题的括号 -7 和 -5。我切换到不同的(更集中的)括号 -6 和 -5.5,这给了我想要的结果:
>> [v,c] = FalsePosition(f,-6,-5.5,10^-6,2)
Method used: Absolute relative approximate error
Brackets: -6 and -5.5
The root is -5.7591
Iterations: 13
v =
-5.7591
c =
13
推荐阅读
- c# - 根据行的总和选择问题
- angular - ViewEncapsulation.ShadowDom 正在创建影子 dom 但不封装来自外部 css 的组件
- python - 每个 ytick 有多个条形的水平条形图
- c++ - 得到 ith,在 O(h) 中,h 是树的高度
- python - 使用 BeautifulSoup 查找 href 链接
- python - 根据单选按钮的一部分打印文本
- javascript - 如何在输入字段中添加必填项并在为空时更改消息错误?
- java - Docker 映像无法将我的 JSON 凭据密钥添加到我的 Google Cloud Natural Language 服务客户端
- amazon-s3 - 如何获得 s3 选择查询以返回单个行
- c - 如何正确释放 SDL_ttf 分配的资源?