if condition not working, any ideas why?
2 views (last 30 days)
Show older comments
Alvaro García
on 24 May 2015
Commented: Alvaro García
on 24 May 2015
%
x=0:0.1:2;
y=12*x.^2+10*x-28;%f(x)
t=-13*x.^2+15*x+28;%g(x)
h=25*x.^2-5*x-56;
plot(x,y,'r',x,t,x,h,'b')
title('intersection point')
xlabel('x-axis')
ylabel('y-axis')
grid on
disp('Initial guesses') %Input for interval one
a=input('first guess: ');
b=input('Second guess: ');
func = @(x) 25*x^2-5*x-56; % f(x)-g(x) = 25*X^2-5*X-56
%----bisection method
for i=1:1000
c=(a+b)/2;
Fc=func(c);
Fb=func(b);
if(Fc*Fb>0)
b=c;
else
a=c;
end
end
disp(c)
funcy = @(x) 12*x^2+10*x-28;
funcg = @(x)-13*x^2+15*x+28;
%y1 = funcy(c);
if funcy(c)== funcg(c)
disp('intersection point') % First intersection point
disp('X:')
disp(c)
%disp('Y:')
%disp(y1)
%hold on
%plot(c,y1,'ro')
else
disp('no')
end
This is the code for the bisection method, the part of the bisection method is working perfectly fine, it displays the value of the intersection, but when i put the condition: if funcy(c)== funcg(c) (which in the calculator it gives me the same answer: 18.72) it displays the else option. I have also tried to change the condition but still the same problem. Thank you for your attention.
1 Comment
Chad Greene
on 24 May 2015
Perhaps there's a typo? Preface your if statement with
funcy(c)
funcg(c)
To make sure Matlab prints the same value for both.
Accepted Answer
Image Analyst
on 24 May 2015
To compare floating point numbers, you need to use a tolerance. See the FAQ: http://matlab.wikia.com/wiki/FAQ#Why_is_0.3_-_0.2_-_0.1_.28or_similar.29_not_equal_to_zero.3F
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!