Need to solve e^x=3*x in tho ways
31 次查看(过去 30 天)
显示 更早的评论
I need to find an interval, wherein is one solution of given equation. I need to solve equation e^x = 3*x in two ways: using Bisection and Newton methods, so I need two codes. My code should also include iteration table and graphic, in which I could see at least some iterations of solution. I already started to program but I'm absolutely new at Matlab and worked a lot so I'm asking for help. Both methods are written for f(x) = e^x - 3*x, but now I need program for e^x = 3x.
This is in Bisection method.
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)')
And this is in Newton method:
clear all
close all
clc
f=@(x) exp(x) - 3*x % Change here for different functions
df=@(x) exp(x) - 3 %this is the derivative of the above function
a=0; b=1;
x=a;
for i=1:1:100
x1=x-(f(x)/df(x));
x=x1;
end
sol=x;
fprintf('Approximate Root is %.15f',sol)
a=0;b=1;
x=a;
er(5)=0;
for i=1:1:5
x1=x-(f(x)/df(x));
x=x1;
er(i)=x1-sol;
end
plot(er)
xlabel('Iteration number')
ylabel('Error')
title('Error vs iteration number')
0 个评论
采纳的回答
更多回答(0 个)
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!