python怎么限制输出精度,Python doctest中限制浮点精度比较的最佳方法

我花时间看了看

doctest

并提出了以下建议。它似乎对我的

float

s是格式化的,但是我非常感谢您对如何使它更健壮、如何传递所有选项等方面的建议(在我的例子中,这是特别容易的,因为

全部的

我的docstring测试将是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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值