Python单元测试:测试两个角度是否几乎相等

2024-05-12 19:13:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我想测试一个函数,它输出以度数为单位的航向,它是一个间隔为[0,360]的数字。由于结果是浮点数,因此将实际结果与预期结果用unittest.assertEqual()进行比较是不起作用的。unittest.assertAlmostEqual()更好,因为它提供了一个公差。这种方法适用于航向不接近0度的情况。在

问题:测试期望值为0度的标题的正确方法是什么?assertAlmostEquals()只包含略大于0度的角,但会忽略略小于0度的角,即360度。。。在


Tags: 方法函数标题间隔情况单位数字unittest
2条回答

您可以使用单位圆上两点之间的欧几里得距离平方和余弦定律来获得两个角度之间的绝对差:

from math import sin, cos, acos
from unittest import assertAlmostEqual        

def assertAlmostEqualAngles(x, y, **kwargs):
    c2 = (sin(x)-sin(y))**2 + (cos(x)-cos(y))**2
    angle_diff = acos((2.0 - c2)/2.0) # a = b = 1
    assertAlmostEqual(angle_diff, 0.0, **kwargs)

这与弧度有关。如果角度以度为单位,则必须进行转换:

^{pr2}$

我也遇到了同样的情况,通过利用模计算,找到了一个更简单的解决方案:

In [20]: def d(a, b):
    ...:     c = (b - a) % 360
    ...:     if c > 180:
    ...:         c -= 360
    ...:     return c
    ...:

In [21]: d(1, 3)
Out[21]: 2

In [22]: d(1, 358)
Out[22]: -3

相关问题 更多 >