How to perform unittest for floating point outputs? - python

Let's say I write unit test for a function that returns a floating point number, I can do it as such in full measure, as in my machine:

>>> import unittest
>>> def div(x,y): return x/float(y)
... 
>>>
>>> class Testdiv(unittest.TestCase):
...     def testdiv(self):
...             assert div(1,9) == 0.1111111111111111
... 
>>> unittest.main()
.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK

Will the same full floating-point precision be the same for OS / distro / machine?

I could try to round up and make unit test as such:

>>> class Testdiv(unittest.TestCase):
...     def testdiv(self):
...             assert round(div(1,9),4) == 0.1111
... 
>>>

I could also argue with log(output), but in order to maintain a fixed decimal precision, I still need to do rounding or truncation.

But in what other way should one pythonically handle unittesting for floating point output?

+4
2

float Python C. / : , 15.1:

( 2000) IEEE-754 , Python IEEE-754 " ".


, , . TestCase.assertAmostEqual:

assertAlmostEqual (, -, place = 7, msg = None, delta = None)

, ( ) , ( 7) . , ( ).

:

import unittest

def div(x, y): return x / float(y)

class Testdiv(unittest.TestCase):
    def testdiv(self):
        self.assertAlmostEqual(div(1, 9), 0.1111111111111111)
        self.assertAlmostEqual(div(1, 9), 0.1111, places=4)

unittest.main() # OK

assert, math.isclose (Python 3.5 +):

import unittest, math

def div(x, y): return x / float(y)

class Testdiv(unittest.TestCase):
    def testdiv(self):
        assert math.isclose(div(1, 9), 0.1111111111111111)

unittest.main() # OK

math.close 1-09, , . ". math.close . PEP 485.

+6

unittest.TestCase float: assertAlmostEqual assertNotAlmostEqual. :

assertAlmostEqual (, -, places = 7, msg = None, delta = None) assertNotAlmostEqual (, -, places = 7, msg = None, delta = None)

, ( ) , ( 7) . , (. round()) .

, ( ).

, :

self.assertAlmostEqual(div(1, 9), 0.1111111111111111)  # round(a-b, 7) == 0
self.assertAlmostEqual(div(1, 9), 0.1111, 4)           # round(a-b, 4) == 0

TestCase.assert* assert, . , , , , .

+3

Source: https://habr.com/ru/post/1612137/


All Articles