Using direct search and Bisection method to find roots above y=40.
2 次查看(过去 30 天)
显示 更早的评论
Question:
Find all locations 𝑥, where the elevation of the roller coaster above ground is ℎ m
(i.e.
𝑦(𝑥) = ℎ). Use the direct search + bisection method WITHOUT using MATLAB
built-in root searching functions. The margin of error for the determined values of
𝑥 must
be under 0.01 mm. Check how close the elevations are at the obtained roots to
ℎ. Indicate
the location of the roots by plotting those on top of the profile plot generated in stage 1.
Parameters:
A=1,B=50, A<x<B
h=40m
F(x)= 50+3.7x^0.7 *sin(0.75x^0.9)
I have a function but it doesn't give me the correct roots.
Code:
xmin=1; xmax=10;
num_points=100;
x=linspace(xmin,xmax,num_points+1);
f=myfun(x);
cnt=0;
h=40;
for i=1:num_points
if f(i)*f(i+1)<h
cnt=cnt+1;
xleft=x(i);
xright=x(i+1);
xmid=(xleft+xright)/2;
fleft=myfun(xleft);
fright=myfun(xright);
iter=0; target_margin_error=0.01e-3;
while 1
fmid=myfun(xmid);
if fleft*fmid<h %root located on left half
xright=xmid;
fright=fmid;
else %root located on right half
xleft=xmid;
fleft=fmid;
end
xmid=(xright+xleft)/2;
fmid_new=myfun(xmid);
margin_error=(xright-xleft)/2;
iter=iter+1;
if margin_error<target_margin_error
fprintf('The root is = %.5f with margin error = %.5e\n',xmid,margin_error)
fprintf('The # of iterations = %d\n',iter)
break
end
end
end
roots=(xmid);
end
%plot
x=linspace(1,10,1000);
y=myfun(x);
figure
plot(x,y)
hold on
hold on
yline(40,'r')
function y=myfun(x)
y=50+3.7*x.^0.7.*sin(0.75*x.^0.9);
end
回答(1 个)
Sam Chak
2023-11-13
Hi @Zainab
I don't understand most part of your cluttered code and your code cannot find the roots. Thus, I have indicated changes made in the code
xmin=1; xmax=50;
num_points=500;
x=linspace(xmin,xmax,num_points+1);
h = 40; % <-- shifted to the line before f
f = myfun(x) - h; % <-- changes
cnt=0;
% plot
xx = linspace(xmin, xmax, 1001); % <-- changes
yy = myfun(xx);
figure
plot(xx, yy)
hold on
yline(40,'r')
for i=1:num_points
if f(i)*f(i+1) < 0 % <-- changes
cnt=cnt+1;
xleft=x(i);
xright=x(i+1);
xmid=(xleft+xright)/2;
fleft=myfun(xleft);
fright=myfun(xright);
iter=0; target_margin_error=0.01e-3;
while 1
fmid=myfun(xmid);
if fleft*fmid<h %root located on left half
xright=xmid;
fright=fmid;
else %root located on right half
xleft=xmid;
fleft=fmid;
end
xmid=(xright+xleft)/2;
fmid_new=myfun(xmid);
margin_error=(xright-xleft)/2;
iter=iter+1;
if margin_error<target_margin_error
plot(xmid, 40, 'x', 'markersize', 12, 'linewidth', 2), hold on
fprintf('The root is = %.5f with margin error = %.5e\n',xmid,margin_error)
fprintf('The # of iterations = %d\n',iter)
break
end
end
end
% roots=(xmid); % <-- unknown
end
function y=myfun(x)
y = 50 + 3.7*(x.^0.7).*sin(0.75*x.^0.9);
end
0 个评论
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
