Unittest (sometimes) fails because floating-point imprecision

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

    By using a floating point value, you accept a small possible imprecision. Therefore, your tests should test if your computed value falls in an acceptable range such as:

    theoreticalValue - epsilon < normalizedValue < theoreticalValue + epsilon
    

    where epsilon is a very small value that you define as acceptable for a variation due to floating point imprecision.

提交回复
热议问题