Monday 25 December 2017

Comparing two floats in python

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.

No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...