Unittest (sometimes) fails because floating-point imprecision

后端 未结 4 1442
自闭症患者
自闭症患者 2021-02-03 17:03

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

4条回答
  •  生来不讨喜
    2021-02-03 17:36

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

提交回复
热议问题