I've just started my first programming course (in a while), and I'm working on the following task:
We are asked to make a function add(x,y) that adds the two arguments. We then implement this function in a testfunction, test_add(), and use an assert statement to make sure the add-function is working correctly. As long as the arguments are integers, all is fine. Then, we are asked to implement a test in our add-function to make sure that 0.1 + 0.2 = 0.3. I've read up on the topic, and know that their representation will be approximated using binary fraction, such that what I'm actually adding is 0.100000000000000005551115123126 + 0.2200000000000000011102230246252 = 0.30000000000000004 and therefore, my testfunction test_add() doesn't pass the pytest. One of the things I've tried is
def add(x,y, tol=1e-9):
if abs(int(x) - x) <= tol:
x == int(x)
if abs(int(y) - y) <= tol:
y == int(y)
return x + y
I've also tried
def add(x,y, tol=1e-9):
if isinstance(x, float):
x == round(x, 1)
if isinstance(y, float):
y == round(y, 1)
return x + y
Still no luck though... any hints on how I can implement this test to pass? Thanks in advance for all help and tips!! :)