python - Python doctest 中限制浮点精度比较的最佳方法

标签 python floating-point doctest

我正在开发一个库的 Python 版本,该库的其他版本都具有良好的结果。因此,我的文档字符串中有一些行,例如

>>> air_f(0,0,0,0.9,300.,1.)
-95019.5943231

精度在所有版本应一致的范围内。如果我在此代码上运行 doctest,它会期望值 -95019.59432308903,该值是一致的,但精度更高。在另一种情况下,8.50371537341e-04 被拒绝,取而代之的是 0.0008503715373413415,它仅多了 1 位精度,但格式不同。

我知道有几种方法可以解决这个问题。我可以检查所有数字并将其更改为完全精度,或者在每个数字之前添加打印格式语句以仅匹配准确性。问题是库中 50 多个单独的文件中的每一个都可以包含数十行这样的行,并且每个文件的特定格式字符串都不同。我见过numtest ,但我不知道它是否成熟(而且我在安装时遇到了麻烦)。

我希望有一些方法可以扩展 build

if __name__ == '__main__':
    import doctest
    doctest.testmod()

以便 doctest 使用较弱的 float 相等性测试。将其添加到 50 个文件中比更改 1000 多行单独的行更易于管理。不过,我不熟悉 doctest,所以我不知道这是否可能或如何继续。想法?

最佳答案

我花了时间查看doctest并得出以下结论。它似乎适用于我的 float 的所有格式化方式,但我绝对会感激有关如何使其更健壮、如何传递所有选项等的建议。(就我而言,它是特别简单,因为我的文档字符串测试的所有都是 float 或 float 列表,所以我没有测试其他用例。)

<小时/>
import doctest

def extractsigfmt(numstr):
    """Find a standard formatter from a string.
    From a string representing a float, find the number of
    significant digits and return a string formatter to standardize
    its representation.
    """
    # Pull out the digits term, removing newline and accounting
    # for either E or e in exponential notation
    digs = numstr.lower().rstrip('\n').split('e')[0]
    # Separate from decimal point, removing sign and leading zeros
    res = digs.split('.')
    if len(res) == 1:
        l, r = res, ''
    else:
        l, r = res
    l = l.lstrip(' -+0')
    nsig = len(l) + len(r)
    # Create a standardized exponential formatter
    fmt = '{:+' + '{0:d}.{1:d}'.format(nsig+6,nsig-1) + 'e}'
    return fmt

# Create new OutputChecker class
class fltOutputChecker(doctest.OutputChecker):
    """OutputChecker customized for floats.
    Overrides check_output to compare standardized floats.
    """
    def check_output(self,want,got,optionflags):
        """Check whether actual output agrees with expected.
        Return True iff the actual output agrees with the expected
        output within the number of significant figures of the
        expected output.
        """
        fmt = extractsigfmt(want)
        want_std = fmt.format(float(want))
        got_std = fmt.format(float(got))
        return (want_std == got_std)

def testfun(n):
    """Function to test new OutputChecker on.
    >>> testfun(0)
    -6.96239965190e+05
    >>> testfun(1)
    8.01977741e-10
    >>> testfun(2)
    -95019.5943231
    >>> testfun(3)
    0.164195952060
    >>> testfun(4)
    -0.687329742959e-3
    >>> testfun(5)
    0.876543210e3
    """
    testlist = [-696239.9651898777,8.01977740740741e-10,
        -95019.59432308903,0.1641959520603997,
        -0.0006873297429586108,876.54320956893102]
    return testlist[n]

# Construct and run doctest on this function
finder = doctest.DocTestFinder()
dtlist = finder.find(testfun)
checker = fltOutputChecker()
runner = doctest.DocTestRunner(checker)
for dt in dtlist:
    runner.run(dt)
results = runner.summarize(verbose=True)

关于python - Python doctest 中限制浮点精度比较的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52965999/

相关文章:

c++ - 为什么我的字符串转换为 float-conversion 不能用 istringstream 得到所有小数?

Python 文档测试错误

python - SECURITY_UNAUTHORIZED_VIEW 未重定向到登录页面

python - 如何在 2D 列表中查找 2x2 对象?

python - 泰坦尼克号管道中的 ValueError

c - 我还是 C 的新手,我不知道为什么我的 float 结果是随机的(也许是类型提升规则?)

java - 双重计算产生奇数结果

python - 使用 Scapy 和 NetFilter 队列接收自定义协议(protocol)数据包

python - 在 python 程序中使用 doctest 和登录

python - 值错误 : wrapper loop when unwrapping