问题
I'm developing a program that makes some floating points calculations. Is there any way to test my functions (which deliver floats) with doctests?
回答1:
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'
'''
回答2:
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
回答3:
The following works for nosetests:
>>> 1/3. # doctest: +ELLIPSIS
0.333...
回答4:
You can use numtest - a doctest extension that simplifies the test of numerical results. https://pypi.python.org/pypi/numtest
>>> 1.0/3
0.333
Failed example: 1.0/3 Expected: 0.333 Got: 0.3333333333333333
>>> 1.0/3 # doctest: +NUMBER
0.333
import doctest
import numtest
doctest.testmod()
Process finished with exit code 0
All tests passed. No need for string formatting in your tests.
回答5:
String format allows use test tuples.
>>> funcreturningfloattuple(1.0)
(1.0, 1.0)
>>> '%.2f, %.2f' % funcreturningfloattuple(1.0)
'1.00, 1.00'
>>> funcreturningfloattuple(1.4)
(1.3999999999999999, 1.3999999999999999)
>>> '%.2f, %.2f' % funcreturningfloattuple(1.4)
'1.40, 1.40'
来源:https://stackoverflow.com/questions/2428618/how-to-test-floats-results-with-doctest