【问题标题】:Making testfunc that allows 0.1 + 0.2 = 0.3使 testfunc 允许 0.1 + 0.2 = 0.3
【发布时间】:2021-11-04 11:52:54
【问题描述】:

我刚刚开始了我的第一门编程课程(不久之后),我正在从事以下任务:

我们被要求创建一个函数 add(x,y) 来添加两个参数。然后我们在测试函数 test_add() 中实现这个函数,并使用断言语句来确保 add-function 正常工作。只要参数是整数,一切都很好。然后,我们被要求在 add-function 中实现一个测试,以确保 0.1 + 0.2 = 0.3。我已经阅读了该主题,并且知道它们的表示将使用二进制分数进行近似,因此我实际添加的是 0.100000000000000005551115123126 + 0.2200000000000000011102230246252 = 0.30000000000000004 并因此,我的测试函数我尝试过的其中一件事是

def add(x,y, tol=1e-9):
    if abs(int(x) - x) <= tol:
        x == int(x)
    if abs(int(y) - y) <= tol:
        y == int(y)
 

    return x + y

我也试过

def add(x,y, tol=1e-9):
   if isinstance(x, float):
        x == round(x, 1)
   if isinstance(y, float):
        y == round(y, 1)
   return x + y

但仍然没有运气......关于我如何实施此测试以通过的任何提示? 提前感谢所有帮助和提示! :)

【问题讨论】:

  • 你使用条件运算符比使用相等吗?
  • 可以分享一下测试代码吗?
  • 我认为您想在test_add() 上指定容差,而不是add()
  • assert(abs(add(.1, .2) - .3) &lt;= 1e-9)
  • 显示作业的实际文本。正确确定问题标准很重要。

标签: python testing floating-point integer


【解决方案1】:

如果您使用的是 Python3.5+,则可以访问 math.isclose() 进行这些类型的比较。

【讨论】:

    【解决方案2】:

    您希望舍入加法的结果,而不是方法的输入。即

    >>> round(.1, 1) + round(.2, 1) == .3
    False
    >>> round(.1 + .2, 1) == .3
    True
    

    所以你的 add 方法可能如下所示:

    def add(x, y):
       return round(x + y, 1)
    
    >>> add(.1, .2) == .3
    True
    

    如果您仍想保留舍入的容差,请将tol 参数更改为要保留的小数位数:

    def add(x, y, tol=9):
        return round(x + y, tol)
    
    >>> add(.1, .2) == .3
    True
    

    另一方面,通常在测试浮点参数时,最好检查边界而不是准确的值。你可以这样做。

    >>> tol = 1e-9
    >>> expected = .3
    >>> actual = .1 + .2
    >>> expected - tol <= actual <= expected + tol
    True
    

    或者更简洁:

    >>> abs(expected - actual) <= tol
    True
    

    【讨论】:

      【解决方案3】:

      如果您希望在函数中计算浮点值,使用 decimal.Decimal 代替此目的可能会有所帮助。

      from decimal import Decimal
      
      def add_decimal(x, y):
          return Decimal(str(x)) + Decimal(str(y))
      
      def add_float(x, y):
          return x + y
      
      a = 0.1
      b = 0.2
      print("Decimal calculation:", add_decimal(a, b))
      print("Float calculation:", add_float(a, b))
      

      输出

      Decimal calculation: 0.3
      Float calculation: 0.30000000000000004
      

      【讨论】:

        猜你喜欢
        • 2020-10-24
        • 2011-10-16
        • 2020-02-15
        • 1970-01-01
        • 1970-01-01
        • 2013-03-10
        • 1970-01-01
        • 2012-01-26
        • 1970-01-01
        相关资源
        最近更新 更多