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 中查找有关 Calculus 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!