Lem*_*ing 8 python math string-formatting
我正在使用python与numpy,scipy和matplotlib进行数据评估.作为结果,我获得了带有错误栏的平均值和拟合参数.
我希望python能够根据给定的精度自动打印这些数据.例如:
假设我得到了结果x = 0.012345 +/- 0.000123
.有没有办法1.235(12) x 10^-2
在指定精度为2时自动格式化.也就是说,计算错误栏中的精度,而不是值.
有没有人知道提供此类功能的软件包,还是我必须自己实现?
有没有办法将其注入python字符串格式化机制?即能写出类似的东西"%.2N" % (0.012345, 0.0000123)
.
我已经查看了numpy和scipy的文档并用Google搜索,但我找不到任何东西.我认为对于处理统计数据的每个人来说,这都是一个有用的功能.
谢谢你的帮助!
编辑:根据内森怀特黑德的要求,我将举几个例子.
123 +- 1 ----precision 1-----> 123(1)
123 +- 1.1 ----precision 2-----> 123.0(11)
0.0123 +- 0.001 ----precision 1-----> 0.012(1)
123.111 +- 0.123 ----precision 2-----> 123.11(12)
Run Code Online (Sandbox Code Playgroud)
为清楚起见,省略了10的幂.括号内的数字是标准错误的简写符号.parens之前的数字的最后一位数字和parens中数字的最后一位必须具有相同的十进制功率.出于某种原因,我无法在网上找到这个概念的好解释.只有我的事情是这家德国Wikpedia文章在这里.但是,它是一种非常常见且非常方便的符号.
EDIT2:我自己实现了速记符号:
#!/usr/bin/env python
# *-* coding: utf-8 *-*
from math import floor, log10
# uncertainty to string
def un2str(x, xe, precision=2):
"""pretty print nominal value and uncertainty
x - nominal value
xe - uncertainty
precision - number of significant digits in uncertainty
returns shortest string representation of `x +- xe` either as
x.xx(ee)e+xx
or as
xxx.xx(ee)"""
# base 10 exponents
x_exp = int(floor(log10(x)))
xe_exp = int(floor(log10(xe)))
# uncertainty
un_exp = xe_exp-precision+1
un_int = round(xe*10**(-un_exp))
# nominal value
no_exp = un_exp
no_int = round(x*10**(-no_exp))
# format - nom(unc)exp
fieldw = x_exp - no_exp
fmt = '%%.%df' % fieldw
result1 = (fmt + '(%.0f)e%d') % (no_int*10**(-fieldw), un_int, x_exp)
# format - nom(unc)
fieldw = max(0, -no_exp)
fmt = '%%.%df' % fieldw
result2 = (fmt + '(%.0f)') % (no_int*10**no_exp, un_int*10**max(0, un_exp))
# return shortest representation
if len(result2) <= len(result1):
return result2
else:
return result1
if __name__ == "__main__":
xs = [123456, 12.34567, 0.123456, 0.001234560000, 0.0000123456]
xes = [ 123, 0.00123, 0.000123, 0.000000012345, 0.0000001234]
precs = [ 1, 2, 3, 4, 1]
for (x, xe, prec) in zip(xs, xes, precs):
print '%.6e +- %.6e @%d --> %s' % (x, xe, prec, un2str(x, xe, prec))
Run Code Online (Sandbox Code Playgroud)
输出:
1.234560e+05 +- 1.230000e+02 @1 --> 1.235(1)e5
1.234567e+01 +- 1.230000e-03 @2 --> 12.3457(12)
1.234560e-01 +- 1.230000e-04 @3 --> 0.123456(123)
1.234560e-03 +- 1.234500e-08 @4 --> 0.00123456000(1235)
1.234560e-05 +- 1.234000e-07 @1 --> 1.23(1)e-5
Run Code Online (Sandbox Code Playgroud)