Unittest(有时)因为浮点不精确而失败

编程入门 行业动态 更新时间:2024-10-23 02:10:31
本文介绍了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(有时)因为浮点不精确而失败

本文发布于:2023-11-27 04:26:43,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:浮点   不精确   Unittest

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!