フィルターのクリア

Strange Problem when i write same code in function

2 ビュー (過去 30 日間)
moonman
moonman 2011 年 11 月 5 日
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');
  1 件のコメント
moonman
moonman 2011 年 11 月 5 日
Thanks a lot Fangjun

サインインしてコメントする。

その他の回答 (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
  1 件のコメント
Walter Roberson
Walter Roberson 2011 年 11 月 5 日
You are not assigning the results of the input() to any variable.

サインインしてコメントする。


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
  1 件のコメント
moonman
moonman 2011 年 11 月 5 日
Problem is resolved now

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeMuPAD についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by