1

I am learning how to use Python 3 for scientific computing. In an exercise, I am asked to implement a function that returns the real or complex roots of a quadratic equation, as well as implementing a test function to verify the accuracy of my function. I am having troubles comparing two floats values.

Here is my function:

def roots(a, b, c):
    from numpy.lib.scimath import sqrt       #Handles real and complex numbers 
    r = sqrt(b**2 - 4*a*c)                     

    sol_1 = (-b + r)/(2*a)
    sol_2 = (-b - r)/(2*a)

    return sol_1, sol_2 

Here is my test_function:

def test_roots_real():
    a = 5; b = 6; c = 1     #test parameters (roots should be -0.2(+) and -1(-)
    exact_sol_1 = -0.2
    exact_sol_2 = -1

    sol_1, sol_2 = roots(a,b,c)
    success = (abs(exact_sol_1 - sol_1) < 1E-14) and (abs(exact_sol_2 - sol_2) < 1E-14)  #Never use == with floats!
    msg = 'Cannot find accurate solutions'
    assert success, msg

test_roots_real()

The problem is when I compare the computed solutions with their respective exact solutions.

If I run roots(5,6,1), I get (-0.20000000000000001, -1.0)

With a threshold of 1E-14, there is no problem (as expected). However, if I change it to something much smaller (e.g. 1E-25), I don't get an error when I should, no? I was wondering what is happening, and I would greatly appreciate the community's feedback.

Thank you!

EDIT:

Also, how could I use the same logic but compare two complex numbers? I never work with them.

Johnathan
  • 1,877
  • 4
  • 23
  • 29
  • 1
    I think it would be better to round to a specified dp during the computation. – Ébe Isaac Nov 15 '16 at 06:14
  • 1
    I don't see how that is a duplicate – Simon Byrne Nov 15 '16 at 09:23
  • 1
    See http://math.stackexchange.com/a/311397 for accurately finding quadratic roots using floating point. – Simon Byrne Nov 15 '16 at 09:25
  • @SimonByrne Thank you very much for your time and help! :) So, the trick is to find the most precise root, and then use algebra to compute the other one. I didn't think about that. – Johnathan Nov 15 '16 at 18:38
  • @ÉbeIsaac Thank you very much! :) My book says: in practice, for most scientific and engineering applications, using a precision of 1E-3 or 1E-4 during computations will avoid floating point errors. This should be acceptable because in those situations, you will have uncertainty anyways. Is this what you suggest? – Johnathan Nov 15 '16 at 18:42
  • More or less, yes. – Ébe Isaac Nov 15 '16 at 18:44

0 Answers0