我如何除以列表 Y 中的变化?

How do I divide by the change in a list Y?

这个问题的解决方案是解决 delta y,请参阅问题底部** **

我正在为许多不同的线性回归方程编写代码。我有两个包含 x 和 y 值的列表。我的一个方程式创建了一个新列表 w。列表 w 的等式是 (w=1/Δy^2),其中 y 是一个列表。我以前使用过需要列表的方程式,但从未使用过列表中的变化。

我有 w = [ 1/(deltay)**2 in zip(x,y)] 但是当我打印时我得到 w [False]。所以我认为我做的 delta y 部分不对,但我不知道。

列表 y 中的每个数据点都需要有 5% 的不确定性。现在我只关心 w 和 y 的不确定性。这个 w 函数是其他东西所需要的。

总而言之,我如何编写等式 (w=1/Δy^2),其中 delta y 是一个列表,w 是一个列表,谢谢。

** 好的,我取得了一些进展。我想我现在知道如何解决这个问题了。我有一个 y 值列表。每个 y 值的不确定性为 5%。所以我需要一个新的列表增量,它是旧列表 y 乘以 0.05。所以我在写这个 deltay = [(i*0.05) for i in zip(y)] 但我收到错误 TypeError: can't multiply sequence by non-int of type 'float'**

我想你的 deltay 变量是 numpy.array otherwise your code will raise an exception, so since you use a numpy.array you could use elementwise operations:

w =  1 / deltay ** 2

如果您的 deltay 不是 numpy.array(如您上次更新所示),您可以使用列表理解来计算您的 w:

deltay = [ i * 0.05 for i in y]
w = [1/x**2 for x in deltay]

原则上你想要的是一个滑动 window 上的迭代器。已经有几个关于这个问题的好帖子 here (Rolling or sliding window iterator?)

我们将使用 Daniel DiPaolo 建议的方法:

from itertools import islice

def window(seq, n=2):
    "Returns a sliding window (of width n) over data from the iterable"
    "   s -> (s0,s1,...s[n-1]), (s1,s2,...,sn), ...                   "
    it = iter(seq)
    result = tuple(islice(it, n))
    if len(result) == n:
        yield result
    for elem in it:
        result = result[1:] + (elem,)
        yield result

现在,更改很容易:

xs = [1, 3, 4, 7, 10, 14]
ys = [3, 1, 2, 9, 13, -1]

# if you need the slope
w = [1/d**2 
     for d in 
         map(lambda pnts: (pnts[1][1]-pnts[0][1])/(pnts[1][0]-pnts[0][0]),  
             window(zip(xs, ys), 2))
    ]

# if you just need the change in y
w = [1/d**2 
     for d in 
         map(lambda y: y[1] - y[0], window(ys, 2))
    ]

回答您的编辑:

Ok I have made some progress. I think I know how to solve this now. I have a list of y values. The uncertainty in each y value is 5%. So I need a new list deltay that is the old list y timesed by 0.05. So I am writing this deltay = [(i*0.05) for i in zip(y)] But I am getting the error TypeError: can't multiply sequence by non-int of type 'float'**

你应该使用 [(i*0.05) for i in y]。如果您使用 zip(y),您迭代的所有条目都将是元组。