Reputation: 263
Help! I dont understand whats happening here.
My code:
function y = bisection(TOL, a, b, f)
pm = (a+b)/2;
fprintf('\t--- METODO de Biseccion ---\n\tFuncion: "%s"\n', char(f));
fprintf('\tIntervalo: [%f,%f]\n',a,b);
fprintf('\t----a----\t----b----\t----pm---\t---f(a)---\t---f(b)---\t---f(pm)---\n');
while (abs(a-b) >= TOL) && (abs(subs(f,pm)+0)>= TOL)
pm = (a+b)/2;
fa = subs(f,a);
fb = subs(f,b);
fpm = subs(f,pm);
fprintf('\t%f,\t%f,\t%f,\t%f,\t%f,\t%f\n',a,b,pm,fa,fb,fpm);
if (fa*fb >= 0 )
error('ERROR, no hay raiz');
end
if ( fpm * fa < 0)
b = pm;
else
if ( fpm * fb <0 )
a = pm;
end
end
end
%disp(pm);
fprintf('\tRaiz: %f\n',pm);
y = pm;
return;
end
And I'm calling the function with this
g = x^2-4*x+4 -(log(x));
p = bisection(10^-2,1,2,g);
I think it has to do with logarithm
Upvotes: 0
Views: 207
Reputation: 469
I'm going to guess- always include the error message verbatim and the context code for better help.
I think you've created g
as a sym
type. You can't use >=
or ge
with syms
because, being symbolic, their are no numbers to compare to.
You could use assume
to set bounds on f
, but I don't think that will work for your application.
Instead of making x
symbolic, make g
an anonymous function.
g = @(x) x^2-4*x+4 -(log(x));
p = bisection(10^-2,1,2,g);
Then, in your function you'll need to replace all occurrences of
subs(f, a);
With
f(a)
Which will evaluate the anonymous function for the value a
.
>> g(2.3)
ans =
-0.7429
Upvotes: 1