-1

I have the next code of the quadratic equation:

if b^2-4*a*c<0 
    disp('No real solutions')
elseif a==0
    x=-c/b
elseif abs(b)==sqrt(b^2-4*a*c)
   w = b+sign(b)*sqrt(b^2-4*a*c);
   x1 = -w/(2*a)
   x2 = -(2*c)/w
else
   x1=(-2*c)/(b+sqrt(b^2-4*a*c))
   x2=(-2*c)/(b-sqrt(b^2-4*a*c))
end

But Matlab doesn't recognize me when b is equal to sqrt(b^2-4*a*c) in some cases, such x^2 -100000001+1, but the equality is true: abs(-100000001)= sqrt((-100000001)^2-4*1*1).

What should I change because Matlab recognize me equality in these extreme cases?

Ali
  • 56,466
  • 29
  • 168
  • 265
Oriol Prat
  • 1,017
  • 1
  • 11
  • 19
  • 2
    `abs(-100000001)` and `sqrt((-100000001)^2-4*1*1)` is not equal. – Daniel Mar 16 '14 at 11:26
  • sqrt((-100000001)^2-4*1*1) in matlab is equal to 1.000000010000000e+08, that this is 100000001.00000, has all the correct significant digits, but I already corrected the method, I established a bound on the sentence and matlab already understood a number exactly equal or a similar number – Oriol Prat Mar 16 '14 at 11:44
  • No, it's not equal. The difference is `-0.00000001999999980000000399999990851...` (calculated using mupad) – Daniel Mar 16 '14 at 11:50
  • @Daniel or possibly even more with standard precision - for `abs(-100000001) - sqrt((-100000001)^2-4*1*1)`, Octave gives me `ans = 2.9802e-008` – Notlikethat Mar 16 '14 at 12:28
  • @Notlikethat: Mupad vpa has a higher precision than octave. – Daniel Mar 16 '14 at 12:29
  • possible duplicate of [Is floating point math broken?](http://stackoverflow.com/questions/588004/is-floating-point-math-broken) – Ali Mar 16 '14 at 13:07
  • @Ali: It's not a duplicate. Both numbers aren't equal. – Daniel Mar 16 '14 at 13:30
  • @Daniel OK, so on the top of that, the question is also wrong as the numbers aren't equal even in exact arithmetic. One more reason to close this question. – Ali Mar 16 '14 at 13:50

1 Answers1

0

Due to the finite numerical precision, Matlab may introduce some small errors. Thus, it is usually better to include some tolerance. For example,

tol = 1e-5;
...
if abs(b-sqrt(b^2-4*a*c))<tol,
% It is considered that both are equal
...
end
tashuhka
  • 5,028
  • 4
  • 45
  • 64