NumPy中的模型测量和误差 [英] Model measurement and error in NumPy
问题描述
我想在实验室实验中尝试使用SciPy套件而不是Octave进行统计. 在这里,回答了我的大多数问题,只剩下另一件事了:
I'd like to try the SciPy suite instead of Octave for doing the statistics in my lab experiments. Most of my questions were answered here, there is just another thing left:
我通常在测量中有一个错误,在八度中,我做了以下事情:
I usually have an error attached to the measurements, in Octave I just did the following:
R.val = 10;
R.err = 0.1;
U.val = 4;
U.err = 0.1;
然后我将像这样计算I
:
I.val = U.val / R.val;
I.err = sqrt(
(1 / R.val * U.err)^2
+ (U.val / R.val^2 * R.err)^2
);
当我进行大量测量时,我通常使用一个结构数组,如下所示:
When I had a bunch of measurements, I usually used a structure array, like this:
R(0).val = 1;
R(0).err = 0.1;
…
R(15).val = 100;
R(15).err = 9;
然后我可以执行R(0).val
或使用R.val
直接访问所有它们,并且我有一个包含所有值的列向量,例如mean(R.val)
.
Then I could do R(0).val
or directly access all of them using R.val
and I had a column vector with all the values, for mean(R.val)
for instance.
我如何使用SciPy/NumPy/Python来表示这一点?
How could I represent this using SciPy/NumPy/Python?
推荐答案
The easiest is indeed to use NumPy structured arrays, that give you the possibility to define arrays of homogeneous elements (a record) composed of other homogeneous elements (fields).
例如,您可以定义
R = np.empty(15, dtype=[('val',float),('err',float)])
,然后填写相应的列:
R['val'] = ...
R['err'] = ...
或者,如果您将val
和err
放在两个列表中,则可以一次定义数组:
Alternatively, you could define the array at once if you have your val
and err
in two lists:
R = np.array(zip(val_list, err_list), dtype=[('val',float),('err',float)])
在两种情况下,您都可以按索引访问单个元素,如R[0]
(这将为您提供特定的对象,np.void
,但仍使您可以单独访问字段),或按切片R[1:-1]
...
In both cases, you can access individual elements by indices, like R[0]
(which would give you a specific object, a np.void
, that still gives you the possibility to access the fields separately), or by slices R[1:-1]
...
以您的示例为例,您可以这样做:
With your example, you could do:
I = np.empty_like(R)
I['val'] = U['val'] / R['val']
I['err'] = np.sqrt((1 / R['val'] * U['err'])**2 + (U['val'] / R['val']**2 * R['err'])**2)
您还可以使用 record array ,它们是基本的结构化数组,其中的__getattr__
和__setattr__
方法被重载,以便您可以将字段作为属性来访问(例如在R.val
中)以及索引(例如标准R['val']
).当然,由于这些基本方法很重载,记录数组的效率不如结构化数组.
You could also use record array, which are basic structured array with the __getattr__
and __setattr__
methods overloaded in such way that you can access the fields as attributes (like in R.val
) as well as indices (like the standard R['val']
). Of course, as these basic methods are overloaded, record arrays are not as efficient as structured arrays.
这篇关于NumPy中的模型测量和误差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!