我很难接受Python的不确定性方案。我必须用python评估实验数据,我已经做了一段时间,但从未遇到过以下问题:
>>>from uncertainties import ufloat
>>>from uncertainties import unumpy as unp
>>>u = ufloat(5, 1)
>>>l = unp.log(u)
>>>print(l)
1.61+/-0.2
一切似乎都很好,对吧?但奇怪的是:
^{pr2}$这是一个很大的问题,因为我就是这样遇到的:
>>>print(l.n)
AttributeError: 'numpy.ndarray' object has no attribute 'n'
现在,在我的工作中,我迫切需要分别用于线性回归的名义值和标准偏差。真正奇怪的是,让我认为它实际上是一个bug,实际上打印变量的工作方式与预期的一样,但是python“认为”它的类型是数组,而实际上它应该是ufloat。在
有什么简单的解决方法吗?你认为这是一个错误,还是我遗漏了什么,实际上是我的错误?在
为了防止任何人问我为什么要做这么简单的计算:这当然只是一个例子。在我的实际工作中,我有许多更复杂的值存储在数组中。在
编辑1:https://pythonhosted.org/uncertainties/user_guide.html
编辑2: 好的,这是我实际遇到问题的代码,上面的代码只是用来说明问题。在
d, t, n = loadtxt('mess_blei_gamma.txt', unpack=True)
fh = open('table_blei.txt', 'w')
nn = []
ln = []
for i in range(0, len(d)):
nn.append(norm(n[i], t[i], n0))
ln.append(unp.log(nn[i]))
fh.write(tex(str(d[i])+" & "+str(t[i])+" & "+str(n[i])+" & "+str(nn[i])+" & "+str(ln[i]))) #works how it's supposed to, the table is perfectly fine
fh.close()
print(unp.nominal_values(nn)) #works fine
print(unp.nominal_values(ln)) #error
首先,许多不常用的对象基本上都是numpy数组:
所以你不必惊讶。
^{pr2}$顺便说一句,ufloat是一个函数,而不是一个类型:
其次,为了得到标称值,应使用:
编辑: 在你编辑了你的原始信息之后,我想我理解你的问题了。你可以用unumpy.log文件在for循环外这样:
我也同意这种行为有点奇怪。在
运行良好并实现目标的代码:
(免责声明:我是《不确定性包》的作者。)
来自
uncertainties.unumpy
模块的数学函数适用于包含不确定数字的NumPy数组(与在数组上使用numpy.log
的方法相同,因为math.log
并不适用于数组)。在在您的示例中,您需要一个简单的不确定度float的日志:
^{pr2}$uncertainties.umath
模块中的There are dedicated functions for this(相当于标准的math
模块):您所观察到的与NumPy在Python标量上使用其数学函数时所做的类似:
相关问题 更多 >
编程相关推荐