Why do I get errors in my bisection algorithm and how can I improve my code?

5 次查看(过去 30 天)
Hi! I'm trying to make this bisection algorithm and can't get it to work. Depending on what I type in I get different kinds of errors. Why do I get the following errors and how can I improve my code into working?
>> x=bisect1(@y.^2,[0,2],1e-7)
Undefined function 'power' for input arguments of type 'function_handle'.
>> x=bisect1(@y*2-5,[0,2],1e-7)
Undefined function 'mtimes' for input arguments of type 'function_handle'.
>> x=bisect1(@y-5,[0,2],1e-7)
Undefined function 'minus' for input arguments of type 'function_handle'.
function x=bisect(f, int , tol )
funktion =@(x) f;
a = int (1); % left end - point
b = int (2); % right end - point
fa =funktion(a) ; % value at left end - point
fb =funktion(b) ; % value at right end - point
disp(fa)
disp(fb)
while b-a > tol % continue as long as the interval is longer
% than the given tolerance
x = (a+b)/2; % compute midpoint on current interval
fx = funktion(x); % compute f(x) at midpoint
if fx==0
return % break and return x
end
if fa * fx < 0 % solution is in left half of interval
b = x; % move right end - point
fb = fx; % move value at right end - point
else % solution is in right half or interval
a = x; % move left end - point
fa = fx; % move value at left end - point
end
end
x = (a+b)/2; % compute midpoint on last interval
disp(x);

采纳的回答

the cyclist
the cyclist 2013-9-10
编辑:the cyclist 2013-9-10
Call your function like this:
f = @(y) y.^2;
x=bisect(f,[0,2],1e-7)
and define your bisect.m function file like this:
function x=bisect(funktion, int , tol )
a = int (1); % left end - point
b = int (2); % right end - point
fa =funktion(a) ; % value at left end - point
fb =funktion(b) ; % value at right end - point
disp(fa)
disp(fb)
while b-a > tol % continue as long as the interval is longer
% than the given tolerance
x = (a+b)/2; % compute midpoint on current interval
fx = funktion(x); % compute f(x) at midpoint
if fx==0
return % break and return x
end
if fa * fx < 0 % solution is in left half of interval
b = x; % move right end - point
fb = fx; % move value at right end - point
else % solution is in right half or interval
a = x; % move left end - point
fa = fx; % move value at left end - point
end
end
x = (a+b)/2; % compute midpoint on last interval
disp(x);

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Debugging and Analysis 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by