Unittest(有时)因为浮点不精确而失败 [英] Unittest (sometimes) fails because floating-point imprecision

查看:175
本文介绍了Unittest(有时)因为浮点不精确而失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类 Vector ,它代表了三维空间中的一个点。这个向量有一个方法 normalize(self,length = 1),它将向量向上/向下缩放为 length == vec.normalize(length) .length



此方法的单元测试有时失败,因为浮点数的不精确性。我的问题是,当方法正确实现时,如何确保这个测试不会失败?是否可以在 没有 的情况下测试近似值?






其他信息

  def testNormalize(self):
vec = Vector(random.random(),random.random(),random.random())
self.assertEqual(vec.normalize 5).length,5)

有时 结果是 AssertionError:4.999999999999999!= 5 AssertionError:5.000000000000001!= 5

$注意:浮点问题可能出现在 Vector.length 属性中,或者在 Vector.normalize()

解决方案

请确保测试有效?



使用 assertAlmostEqual assertNotAlmostEqual



官方文档

  assertAlmostEqual(first ,第二,places = 7,msg = None,delta = None)

第二个是大致相等的计算差异,四舍五入到给定的小数位数(默认7),并比较为零。



2)是它可能做到这一点,而不需要测试一个近似值?



基本上没有。



浮点问题不能被绕过,所以你必须把 vec.normalize 或接受一个几乎相等的结果(两者中的每一个都是近似值)。

I have a class Vector that represents a point in 3-dimensional space. This vector has a method normalize(self, length = 1) which scales the vector down/up to be length == vec.normalize(length).length.

The unittest for this method sometimes fails because of the imprecision of floating-point numbers. My question is, how can I make sure this test does not fail when the methods are implemented correctly? Is it possible to do it without testing for an approximate value?



Additional information:

    def testNormalize(self):
        vec = Vector(random.random(), random.random(), random.random())
        self.assertEqual(vec.normalize(5).length, 5)

This sometimes results in either AssertionError: 4.999999999999999 != 5 or AssertionError: 5.000000000000001 != 5.

Note: I am aware that the floating-point issue may be in the Vector.length property or in Vector.normalize().

解决方案

1) How can I make sure the test works?

Use assertAlmostEqual, assertNotAlmostEqual.

From the official documentation:

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

Test that first and second are approximately equal by computing the difference, rounding to the given number of decimal places (default 7), and comparing to zero.

2) Is it possible to do it without testing for an approximate value?

Esentially No.

The floating point issue can't be bypassed, so you have either to "round" the result given by vec.normalize or accept an almost-equal result (each one of the two is an approximation).

这篇关于Unittest(有时)因为浮点不精确而失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆