Python 不确定 Unumpy 类型的错误?

Python Uncertainties Unumpy type bug?

我很难接受 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

一切似乎都还好吧?但奇怪的部分来了:

>>>print(type(l))
<type 'numpy.ndarray'>

这是一个巨大的问题,因为我就是这样遇到的:

>>>print(l.n)
AttributeError: 'numpy.ndarray' object has no attribute 'n'

现在在我的工作中,我迫切需要分别用于线性回归的标称值和标准差。这真的很奇怪并且让我认为它实际上是一个错误是事实,打印变量实际上按预期工作但是 python "thinks" 它的类型是一个数组,而它实际上应该是一个 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

首先,很多unumpy对象基本上都是numpy数组:

>>>arr = unp.uarray([1, 2], [0.01, 0.002])
>>>arr
[1.0+/-0.01 2.0+/-0.002]
>>>type(arr)
<type 'numpy.ndarray'>

所以你不应该感到惊讶。
顺便说一下,ufloat 是一个函数而不是类型:

>>>x = ufloat(0.20, 0.01)  # x = 0.20+/-0.01
>>>print type(x)
<class 'uncertainties.Variable'>
>>>type(ufloat)
<type 'function'>

其次,为了获得标称值,您应该使用:

unumpy.nominal_values(l)

编辑: 在您编辑原始消息后,我想我明白了您的问题。您可以像这样在 for 循环外使用 unumpy.log:

>>>nn = [ ufloat(1, 2), ufloat(53, 4)]
>>>ln = unp.log(nn)
>>>ln
[0.0+/-2.0 3.970291913552122+/-0.07547169811320754]
>>>type(ln)
<type 'numpy.ndarray'>
>>>(unp.nominal_values(ln)) #now it works fine
[ 0.          3.97029191]

我也同意这种行为有点奇怪。

运行良好并实现目标的代码:

d, t, n = loadtxt('mess_blei_gamma.txt', unpack=True)
fh = open('table_blei.txt', 'w')
nn = (norm(n[i], t[i], n0) for i  range(0, len(d)))
ln = unp.log(nn)
for i in range(0, len(d)):
    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)) 
print(unp.nominal_values(ln)) 

(免责声明:我是不确定性包的作者。)

uncertainties.unumpy 模块中的数学函数用于包含不确定数字的 NumPy 数组(与在数组上使用 numpy.log 的方式相同因为 math.log 不适用于数组)。

在您的示例中,您想要的是具有不确定性的简单 float 的日志:

>>> from uncertainties import ufloat
>>> u = ufloat(5, 1)

There are dedicated functions for thisuncertainties.umath 模块中(相当于标准的 math 模块):

>>> from uncertainties.umath import log
>>> log_value = log(u)  # This is a UFloat, like u (and not a 1-element array)
>>> print log_value.n  # Nominal value, as expected

当您在 Python 标量上使用它的数学函数时,您观察到的与 NumPy 所做的类似:

>>> numpy.log(3)
1.0986122886681098
>>> type(_)  # Not a Python float!
<type 'numpy.float64'>