[英]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?
有没有办法用doctests测试我的函数(提供浮点数)?
Sure, just format the floats with a reasonable format, based on your knowledge of what precision you expect them to exhibit -- eg, if you expect accuracy to 2 digits after the decimal point, you could use: 当然,只需根据您对预期显示精度的了解,以合理的格式格式化浮点数 - 例如,如果您希望精度达到小数点后的2位数,则可以使用:
''' Rest of your docstring and then...
>>> '%.2f' % funcreturningfloat()
'123.45'
'''
The following works for nosetests: 以下适用于nosetests:
>>> 1/3. # doctest: +ELLIPSIS
0.333...
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.
浮点数也会受到跨平台的小输出变化的影响,因为Python遵循平台C库进行浮点格式化,而C库的质量差别很大。
>>> 1./7 # risky
0.14285714285714285
>>> print 1./7 # safer
0.142857142857
>>> print round(1./7, 6) # much safer
0.142857
You can use numtest - a doctest extension that simplifies the test of numerical results. 您可以使用numtest - doctest扩展,简化数值结果的测试。 https://pypi.python.org/pypi/numtest
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预期:0.333得到:0.3333333333333333
>>> 1.0/3 # doctest: +NUMBER
0.333
import doctest
import numtest
doctest.testmod()
Process finished with exit code 0
进程以退出代码0结束
All tests passed. 所有测试都通过了 No need for string formatting in your tests.
在测试中不需要字符串格式化。
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'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.