Strange Problem when i write same code in function

1 次查看(过去 30 天)
This is my original code for Bisection Methods of Numerical Analysis
% A program in matlab
% bisection method to find the roots of x^3+x^3+5=0
xleft = -2.5 ; xright = -1.5 ; n = 20
format longe
% Input: xleft,xright = left and right brackets of the root
% n = (optional) number of iterations; default: n =15
% Output: x = estimate of the root
if nargin<3, n=15; end % Default number of iterations
a = xleft; b =xright; % Copy orig bracket to local variables
fa = a^3 + a^2 + 5; % Initial values
fb = b^3 + b^2 +5; % Initial values
fprintf(' k a xmid b f(xmid)\n');
for k=1:n
xm = a + 0.5*(b-a); % Minimize roundoff in the midpoint
fm = xm^3 + xm^2 +5; % f(x) at midpoint
fprintf('%3d %12.8f %12.8f %12.8f %12.3e\n',k,a,xm,b,fm);
if sign(fm) == sign(fa)
a = xm; fa = fm;
else
b = xm; fb = fm;
end
end
**************************************** Now i am writing the same function by manually giving input
my main file is this one
input('Type value of a \n');
input('Type value of b\n');
bisec(a,b)
and my function file is this one
function bisec(a,b)
format longe
n=20;
% Output: x = estimate of the root
*fa = a^3 + a^2 + 5; % Initial values
fb = b^3 + b^2 +5; % Initial values* _ITALIC TEXT_
fprintf(' k a xmid b f(xmid)\n');
for k=1:n
xm = a + 0.5*(b-a); % Minimize roundoff in the midpoint
fm = xm^3 + xm^2 +5; % f(x) at midpoint
fprintf('%3d %12.8f %12.8f %12.8f %12.3e\n',k,a,xm,b,fm);
if sign(fm) == sign(fa)
a = xm; fa = fm;
else
b = xm; fb = fm;
end
end
end
But my results are comming different plz guide me

采纳的回答

Fangjun Jiang
Fangjun Jiang 2011-11-5
try
a=input('Type value of a \n');
b=input('Type value of b\n');

更多回答(2 个)

moonman
moonman 2011-11-5
Thanks a lot Fangjun u saved my time and problem is resolved Can u explain what is wrong in my input commands

moonman
moonman 2011-11-5
I also need one more help. I have to follow this instruction
write a separate function file called f.m that stores the definition of the function: for part (i) this will be function y=f(x) y=x.^3+x.^2+5; You can then use f(x) in your bisection M-file
Right now i am writing this function manually and it is shown in italic

类别

Help CenterFile Exchange 中查找有关 MuPAD 的更多信息

标签

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by