Why won't my code run.

1 次查看(过去 30 天)
me
me 2015-9-16
My code keeps giving me the error
Error using bisec (line 5) Not enough input arguments.
I don't understand what am doing wrong.
function m = bisec(f, low, high, tol)
disp('Here Bisection Method Starts: ');
% evaluating both intervals
y1 = feval(f, low);
y2 = feval(f, high);
i = 0;
% error handling
if y1 * y2 > 0
disp('sorry not correct values given...');
m = 'Error'
return
end
% start bisection method until nearer to zero
while (abs(high - low) >= tol)
i = i + 1;
% Getting new value to test for root
m = (high + low)/2;
y3 = feval(f, m);
if y3 == 0
return
end
% Update limits
if y1 * y3 > 0
low = m;
y1 = y3;
else
high = m;
end
end
% Printing final results
w = feval(f, m);
fprintf('\n x = %f produces f(x) = %f \n %i iterations\n', m, y3, i-1);
fprintf(' Approximation with tolerance = %f \n', tol);

回答(1 个)

James Tursa
James Tursa 2015-9-16
编辑:James Tursa 2015-9-16
How are you calling bisec? From the error message, it looks like you are not providing all of the inputs. E.g., if you only did bisec(@myFunction) then that would only be one input, and then bisec would complain when it tried to use low because it wasn't input to the function.
A nit: If y1 or y2 start out exactly 0, your code doesn't detect this immediate solution.
  6 个评论
me
me 2015-9-16
also how do i call the function if f=sin(x)+x
James Tursa
James Tursa 2015-9-16
编辑:James Tursa 2015-9-16
You don't need to test for low>high since your code will work regardless of the order they are input (try it!). But testing for low==high makes sense. Note that if low==high then sign(y1)==sign(y2) will also be true, so that implies sign(y1)*sign(y2)==1. So the 2nd test covers the case for low==high. So maybe something like this:
if( sign(y1)*sign(y2) == 1 )
error('Invalid inputs. low==high or signs of function results are the same');
end
But keep in mind my earlier comment about y1==0 or y2==0 being detected for immediate solution. Also note that I used the "error" function. This is the normal way for a function to stop with an error as it forces the calling function to either stop or to deal with the error. Doing "m = 'Error'" as you are currently doing simply returns a value back to the caller that may in fact get used downstream by the caller as an actual valid result, producing garbage results. It relies on a user actually looking at the screen to tell that something went wrong. This is not a good way for your function to report an error since it makes unsafe assumptions about the caller.
To use f=sin(x)+x you could do this (anonymous function handle):
f = @(x)sin(x)+x
Then pass in f as the first argument. E.g., see this link:

请先登录,再进行评论。

类别

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

Community Treasure Hunt

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

Start Hunting!

Translated by