Unittest (sometimes) fails because floating-point imprecision

后端 未结 4 1443
自闭症患者
自闭症患者 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:31

    In general, you should not assert equality for floats. Instead, ensure that the result is within certain bounds, e.g.:

    self.assertTrue(abs(vec.normalize(5).length - 5) < 0.001)
    

提交回复
热议问题