While loop in function
2 ビュー (過去 30 日間)
古いコメントを表示
This is my function code:
function [i, epsilon_a,x_sol] = secant_hyy(f,epsilon_c,x_var_1,x_var_2)
syms x;
i = 3;
x_sol(1) = x_var_1;
x_sol(2) = x_var_2;
while 1
x_sol(i) = x_sol(i-1) - subs(f,x_sol(i-1)) * (x_sol(i-2)-x_sol(i-1)) / (subs(f,x_sol(i-2))-subs(f,x_sol(i-1)));
epsilon_a(i) = ((x_sol(i)-x_sol(i-1)) / x_sol(i) )* 100 ;
fprintf("x_sol %f değeri: %f \n ",i,x_sol(i));
fprintf("x_sol %f hata oranı %f \n ",i,epsilon_a(i));
if epsilon_a(i) < 1
break;
end
i = i + 1;
end
end
This is the main code:
clear;
clc;
%known veriables
syms x
f(x) = exp(-x) - x;
eqn = f(x) == 0;
mat_sol = solve(eqn,x);
x_var_1 = 1;
x_var_2 = 2;
epsilon_c = 1;
[i, epsilon_a,x_sol] = secant_hyy(f,epsilon_c,x_var_1,x_var_2);
This is the solution:
x_sol 3.000000 değeri: 0.487142
x_sol 3.000000 hata oranı -310.558199
>!The code results only calculates for first i value and loop doesn't work. I didn't get where the error was.
0 件のコメント
採用された回答
Voss
2023 年 11 月 16 日
The first iteration of the while loop produces an epsilon_a(i) of -310.558, which is less than 1, so the loop terminates (the termination criterion is epsilon_a(i) < 1).
If you change the termination criterion to abs(epsilon_a(i)) < 1, then the loop iterates a few times and maybe gives the result you are hoping for?
% This is the main code:
clear;
clc;
%known veriables
syms x
f(x) = exp(-x) - x;
eqn = f(x) == 0;
mat_sol = solve(eqn,x);
x_var_1 = 1;
x_var_2 = 2;
epsilon_c = 1;
[i, epsilon_a,x_sol] = secant_hyy(f,epsilon_c,x_var_1,x_var_2);
function [i, epsilon_a,x_sol] = secant_hyy(f,epsilon_c,x_var_1,x_var_2)
syms x;
i = 3;
x_sol(1) = x_var_1;
x_sol(2) = x_var_2;
while 1
x_sol(i) = x_sol(i-1) - subs(f,x_sol(i-1)) * (x_sol(i-2)-x_sol(i-1)) / (subs(f,x_sol(i-2))-subs(f,x_sol(i-1)));
epsilon_a(i) = ((x_sol(i)-x_sol(i-1)) / x_sol(i) )* 100 ;
fprintf("x_sol %f değeri: %f \n ",i,x_sol(i));
fprintf("x_sol %f hata oranı %f \n ",i,epsilon_a(i));
if abs(epsilon_a(i)) < 1
break;
end
i = i + 1;
end
end
0 件のコメント
その他の回答 (1 件)
Les Beckham
2023 年 11 月 16 日
Perhaps you meant to test the absolute value of epsilon_a?
%known veriables
syms x
f(x) = exp(-x) - x;
eqn = f(x) == 0;
mat_sol = solve(eqn,x);
x_var_1 = 1;
x_var_2 = 2;
epsilon_c = 1;
[i, epsilon_a,x_sol] = secant_hyy(f,epsilon_c,x_var_1,x_var_2);
function [i, epsilon_a,x_sol] = secant_hyy(f,epsilon_c,x_var_1,x_var_2)
syms x;
i = 3;
x_sol(1) = x_var_1;
x_sol(2) = x_var_2;
while 1
x_sol(i) = x_sol(i-1) - subs(f,x_sol(i-1)) * (x_sol(i-2)-x_sol(i-1)) / (subs(f,x_sol(i-2))-subs(f,x_sol(i-1)));
epsilon_a(i) = ((x_sol(i)-x_sol(i-1)) / x_sol(i)) * 100 ;
fprintf("x_sol %f değeri: %f\n", i, x_sol(i));
fprintf("x_sol %f hata oranı %f\n", i, epsilon_a(i));
if abs(epsilon_a(i)) < 1
break;
end
i = i + 1;
end
end
0 件のコメント
参考
カテゴリ
Help Center および File Exchange で Loops and Conditional Statements についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!