Unittest (sometimes) fails because floating-point imprecision

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

    I suppose one possibility is to apply the function to test cases for which all inputs, the results of all intermediate calculations, and the output are exactly representable by float.

    To illustrate:

    In [2]: import math
    
    In [4]: def norm(x, y):
       ...:     return math.sqrt(x*x + y*y)
       ...: 
    
    In [6]: norm(3, 4) == 5
    Out[6]: True
    

    Not sure how practical this is though...

提交回复
热议问题