-1

I had an addition function defined in python and when i ran unit test using the python unittest module , floating point addition test case failed. is there any reference to a good python module which handles the floating point arthematic easy.

Appreciate your help in resolving the error in addition function to return till nonzero numbers after the decimal.

I tried to round the result and run the test , and also tried to cast expected result into float.

p3.py

def addition(a,b):
    return a + b

and unit test cases for the function is defined in p3_test.py

import unittest
from  p3 import addition

class TestAddition(unittest.TestCase):
    def test_Addition(self):
        self.assertEqual(addition(2, 3), 5)
        self.assertEqual(addition(0, -1), -1)
        self.assertEqual(addition(-1, 0.99), -0.01)

The third test case fails with below error:

    self.assertEqual(addition(-1, 0.99), float(0.01))
AssertionError: -0.010000000000000009 != 0.01

----------------------------------------------------------------------
Ran 1 test in 0.000s

Expectation it that all test cases should pass

Raja Bala
  • 1
  • 2

1 Answers1

0

I understand the floating point representation is the cause of the issue in my case, since i am looking for an appropriate way to solve the unit test for the same. i found a approximation assert method in unittest module which solves the issue.

here is the new piece of code.

import unittest
from  p3 import addition

class TestAddition(unittest.TestCase):
    def test_Addition(self):
        self.assertEqual(addition(2, 3), 5)
        self.assertEqual(addition(0, -1), -1)
        self.assertAlmostEqual(addition(-1, 0.99), -0.01, 7)
Raja Bala
  • 1
  • 2