【问题标题】:Python Uncertainties Module, ufloat can't unpack variablePython不确定性模块,ufloat无法解压变量
【发布时间】:2013-10-27 17:25:34
【问题描述】:

我正在使用 python 2.7 和名为“不确定性”的模块来分析实验数据。我有两个数组,polycoeffs 和 cov,它们是由 numpy 函数 polyfit 生成的。我已经设法从 cov 数组中提取了前导对角线,并且我试图将这些值与名为 uncert_coeffs 的列表中的适当系数与不确定性函数“ufloat”进行匹配。代码如下:

polycoeffs,cov=polyfit(wav,trans,6,cov=True) #wav and trans are themselves, arrays.
print  "Polycoeffs= ",polycoeffs

print "Cov= ",cov

cov_diag=[]
for element in diag(cov):
    cov_diag.append(str(element))
print "The diagonal of the covariant matrix= ",cov_diag
ord_counter=6
uncert_coeffs=[]
cov_index=0

for i in polycoeffs:
    uncert=(cov_diag[cov_index])
    print "uncert: ",uncert
    temp=ufloat("(i+/-uncert)") #error here
    uncert_coeffs.append(temp)
    cov_index+=1

print "The polynomial coefficients with uncertainties, are: ",uncert_coeffs 

这会产生错误:

ValueError: Cannot parse (i+/-uncert): was expecting a number like 1.23+/-0.1

所以我的问题是:在这种情况下,手动组合 polycoeff 和它们的不确定性会非常痛苦,我怎样才能让 ufloat 解包变量 uncert?此外,uncert 的值大多是科学计数法。

【问题讨论】:

    标签: python numpy uncertainty


    【解决方案1】:

    您传递的是文字字符串 "i+/-uncert" 而不是变量值。

    假设您使用的是最新版本的不确定性,请执行以下操作:

    temp = ufloat(i, uncert)
    

    或者,您可以将数值格式化为它们的字符串表示形式:

    temp = ufloat('{}+/-{}'.format(i, uncert))
    

    但是,没有理由不直接将值传递给ufloat

    【讨论】:

    • 我似乎从 Debian 存储库获得了 1.8 版,并且我还按照建议传递了错误的参数。它在 2.4 版中运行良好。
    • 使用不确定性 2.4 模块,这现在可以在 python idle 中使用,但在从终端调用脚本时不起作用。我收到错误用户警告:要么使用 ufloat(blah,blah) 要么使用 ufloat(etc)。我完全按照你的建议来称呼它。
    • @user2151741 - 这是警告而不是错误。它应该仍然运行,它只是让你知道你正在做的事情在以后的版本中将不受支持。根据您的代码,这可能是因为您将所有内容都转换为字符串(例如cov_diag.append(str(element)))。尝试只传递实际的浮点数。
    • 我已经将这一行修改为 cov_diag.append(element) 但我仍然收到我在上一条评论中没有提到的错误:AttributeError: 'numpy.float64' object has no attribute 'strip '。我尝试使用不确定性函数 wrap 即:poly_wrap=polyfit.wrap() 但这也会引发错误 'function' object has no attribute 'wrap'。
    • 您得到AttributeError 是因为您尝试对数值使用strip 方法。您对字符串和数字类型(例如浮点数)感到困惑。 Python 是一种“强类型”语言。换句话说,一切都有一个类型,你需要在类型之间显式转换。字符串有一个strip 方法来删​​除空格。浮点数没有(这没有任何意义),因此当您尝试剥离浮点数时会出现错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多