Function to determine if two numbers are nearly equal when rounded to n significant decimal digits

前端 未结 11 1897

I have been asked to test a library provided by a 3rd party. The library is known to be accurate to n significant figures. Any less-significant errors can safely be

11条回答
  •  广开言路
    2020-12-03 02:51

    There are already plenty of great answers, but here's a think:

    def closeness(a, b):
      """Returns measure of equality (for two floats), in unit
         of decimal significant figures."""
      if a == b:
        return float("infinity")
      difference = abs(a - b)
      avg = (a + b)/2
      return math.log10( avg / difference )
    
    
    if closeness(1000, 1000.1) > 3:
      print "Joy!"
    

提交回复
热议问题