How to test floats results with doctest?

大兔子大兔子 提交于 2021-02-07 05:01:08

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!