【发布时间】:2015-09-20 02:23:17
【问题描述】:
我是 MATLAB 新手,我想知道为什么我的二分法代码无法运行,代码如下:
function [ r ] = bisection1( f1, a, b, N, eps_step, eps_abs )
% Check that that neither end-point is a root
% and if f(a) and f(b) have the same sign, throw an exception.
if ( f1(a) == 0 )
r = a;
return;
elseif ( f1(b) == 0 )
r = b;
return;
elseif ( f1(a) * f1(b) > 0 )
error( 'f(a) and f(b) do not have opposite signs' );
end
% We will iterate N times and if a root was not
% found after N iterations, an exception will be thrown.
for k = 1:N
% Find the mid-point
c = (a + b)/2;
% Check if we found a root or whether or not
% we should continue with:
% [a, c] if f(a) and f(c) have opposite signs, or
% [c, b] if f(c) and f(b) have opposite signs.
if ( f1(c) == 0 )
r = c;
return;
elseif ( f1(c)*f1(a) < 0 )
b = c;
else
a = c;
end
% If |b - a| < eps_step, check whether or not
% |f(a)| < |f(b)| and |f(a)| < eps_abs and return 'a', or
% |f(b)| < eps_abs and return 'b'.
if ( b - a < eps_step )
if ( abs( f1(a) ) < abs( f1(b) ) && abs( f1(a) ) < eps_abs )
r = a;
return;
elseif ( abs( f1(b) ) < eps_abs )
r = b;
return;
end
end
end
error( 'the method did not converge' );
end
我定义了
function y=f1(x)
y=x^3+x-3;
end
在另一个脚本中,但是当我输入 bisection1(f1,1,2,100,10^-6,10^-6) 时它没有运行。
你能帮我完成这个任务吗?
【问题讨论】:
-
您应该回到获得此代码的 MATLAB 书籍。
f1现在也是一个函数,需要输入参数,这意味着您不能将它作为参数传递给bisection1。 -
Right :) 但后来我尝试了 bisection1(f1(x),1,2,100,10^-6,10^-6) 并没有奏效。
标签: matlab