python - 如何对浮点输出执行单元测试? - Python

标签 python unit-testing testing floating-point precision

假设我正在为一个返回 float 的函数编写单元测试,我可以按照我的机器完全精确地进行测试:

>>> 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

相同的完整浮点精度在操作系统/发行版/机器上是否相同?

我可以尝试四舍五入并进行这样的单元测试:

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

我也可以使用 log(output) 进行断言,但为了保持固定的小数精度,我仍然需要进行舍入或截断。

但是,还有什么其他方法可以用 Python 方式处理浮点输出的单元测试呢?

最佳答案

Python 中float 的精度取决于底层的C 表示。来自 Tutorial/Floating Point Arithmetic: Issues and Limitations, 15.1 :

Almost all machines today (November 2000) use IEEE-754 floating point arithmetic, and almost all platforms map Python floats to IEEE-754 “double precision”.


至于测试,更好的想法是使用现有功能,例如TestCase.assertAlmostEqual :

assertAlmostEqual(first, second, places=7, msg=None, delta=None)

Test that first and second are approximately (or not approximately) equal by computing the difference, rounding to the given number of decimal places (default 7), and comparing to zero. If delta is supplied instead of places then the difference between first and second must be less or equal to (or greater than) delta.

例子:

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 的默认相对公差是 1e-09,“这确保两个值在大约 9 个小数位内相同。”。有关 math.close 的更多信息,请参阅 PEP 485 .

关于python - 如何对浮点输出执行单元测试? - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33199548/

相关文章:

Python unittest : to mock. patch() 或者只是用 Mock 替换方法?

java - 我无法在不暴露私有(private)字段的情况下对我的类进行单元测试——我的设计有问题吗?

unit-testing - 如何测试 Go 的 "testing"包函数?

python - 身份验证失败 : [Errno 1] _ssl. c:510: 错误:14090086:SSL 例程:SSL3_GET_SERVER_CERTIFICATE:证书验证失败

python - 如何在 Windows 上将 python 请求与 Putty SOCKS 代理一起使用?

python - 如何在Python中找到分类神经网络的预测输出?

c++ - 单元测试访问者模式架构

unit-testing - Nodejs 单元测试网址

perl - 测试使用 Dist::Zilla 的 XS 模块

python - 我不明白有什么问题 InvalidArgumentError : Conv2DCustomBackpropInputOp only supports NHWC