Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test floats results with doctest?

I'm developing a program that makes some floating points calculations. Is there any way to test my functions (which deliver floats) with doctests?

like image 449
malev Avatar asked Mar 11 '10 20:03

malev


People also ask

Can doctest be used to test docstrings?

There are several common ways to use doctest: To check that a module's docstrings are up-to-date by verifying that all interactive examples still work as documented. To perform regression testing by verifying that interactive examples from a test file or a test object work as expected.

Can we handle unpredictable output using doctest?

When the tests include values that are likely to change in unpredictable ways, and where the actual value is not important to the test results, you can use the ELLIPSIS option to tell doctest to ignore portions of the verification value.

What is doctest used for?

doctest is a module included in the Python programming language's standard library that allows the easy generation of tests based on output from the standard Python interpreter shell, cut and pasted into docstrings.


Video Answer


2 Answers

Sure, just format the floats with a reasonable format, based on your knowledge of what precision you expect them to exhibit -- e.g, if you expect accuracy to 2 digits after the decimal point, you could use:

''' Rest of your docstring and then...

    >>> '%.2f' % funcreturningfloat()
    '123.45'

'''
like image 131
Alex Martelli Avatar answered Sep 19 '22 02:09

Alex Martelli


The documentation has a suggestion

Floating-point numbers are also subject to small output variations across platforms, because Python defers to the platform C library for float formatting, and C libraries vary widely in quality here.

>>> 1./7  # risky
0.14285714285714285
>>> print 1./7 # safer
0.142857142857
>>> print round(1./7, 6) # much safer
0.142857
like image 37
John La Rooy Avatar answered Sep 21 '22 02:09

John La Rooy