f(x) = e^x-3x matlab code
显示 更早的评论
I want to write a matlab script that finds solutions of function f(x) = e^x - 3x. I tried to write some code. My matlab code should include iteration table and graphic of function. Can anyone help me please with a code or give me advices?
f=@(x) exp(x) - 3*x ;
a = 0; b = 1;tol = 1e-8;
if (f(a)*f(b) > 0)
error ('invalid choice of interval')
end
r=0; n=0;
while ((b-a)/2 > 0)
n = n + 1;
r = (a+b)/2;
if (f(r) == 0)
break;
elseif (f(a)*f(r) <= 0)
b = r ;
else
a = r;
end
end
3 个评论
Matt J
2018-2-25
solutions of function f(x) = e^x - 3x
I think what you really mean is, solutions of the equation
exp(x) - 3*x = 0
Adomas Bazinys
2018-2-25
Rik
2018-2-25
Did you read Steven Lord's comment? Your current code finds 1 solution to this equation already.
If you have some restriction (e.g. because this is a homework assignment), please mention them.
采纳的回答
更多回答(2 个)
Rik
2018-2-25
If you want to store intermediate result, us the n for indexing. Also, don't you mean if abs(f(r(n)))<=tol? Then you would actually use the variable tol.
f=@(x) exp(x) - 3*x ;
a = 0; b = 1;tol = 1e-8;
if (f(a)*f(b) > 0)
error ('invalid choice of interval')
end
r=0; n=0;
while ((b-a)/2 > 0)
n = n + 1;
r(n) = (a+b)/2;%#ok suppress warning, we can't know the length of r in advance
if (f(r(n)) == 0)
%if abs(f(r(n)))<=tol
break;
elseif (f(a)*f(r(n)) <= 0)
b = r(n) ;
else
a = r(n);
end
end
it_table=[r' f(r)'];
clc
disp(it_table)
figure(1),clf(1)
plot(1:numel(r),f(r))
xlabel('Iteration number'),ylabel('f(r)')
maryam
2022-10-25
0 个投票
Find an approximation to within 0.00001 to a value in [0, 1] with 𝑓(𝑥) = 𝑒 𝑥 − 𝑥 2 + 3𝑥 − 2 = 0 Use Bisection method
1 个评论
Walter Roberson
2022-10-25
No, that will certainly not solve the question posted by Adomas
类别
在 帮助中心 和 File Exchange 中查找有关 Common Operations 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
