Python的不确定性异常类型错误?

2024-10-02 04:22:04 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Tags: 代码fromimportlog编辑错误nn数组
2条回答

首先,许多不常用的对象基本上都是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是一个函数,而不是一个类型:

^{pr2}$

其次,为了得到标称值,应使用:

unumpy.nominal_values(l)

编辑: 在你编辑了你的原始信息之后,我想我理解你的问题了。你可以用unumpy.log文件在for循环外这样:

>>>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)

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

^{pr2}$

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

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

相关问题 更多 >

    热门问题