Reputation: 35
Solution to this problem is solving delta y, see bottom of question in ** **
I am writing code for many different equations for linear regression. I have two lists with x and y values. One of my equations creates a new list w. The equation for the list w is (w=1/Δy^2) where y is a list. I have used equations that require lists before but never the change in a list.
I have w = [ 1/(deltay)**2 in zip(x,y)]
But when I print that I get w [False]
. So I dont think I am doing the delta y part right but I have no idea.
Each data point in the list y needs to have an uncertainty of 5%. Right now I am only concerned with w and the uncertainty in y. This w function is needed for something else.
In summary how can I code the equation (w=1/Δy^2) where delta y is a list and w is a list, thanks.
** 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'**
Upvotes: 1
Views: 76
Reputation: 17322
I suppose that your deltay
variable is a 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
if your deltay
it is not a numpy.array (as your last update shows) you can use list comprehension to compute your w
:
deltay = [ i * 0.05 for i in y]
w = [1/x**2 for x in deltay]
Upvotes: 1
Reputation: 1257
In principle what you want to have is an iterator over a sliding window. There are already several good posts on that matter available here (Rolling or sliding window iterator?).
We will make use of Daniel DiPaolo's suggested approach:
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
Now, getting the changes is easy:
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))
]
To answer your edit:
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'**
You should use [(i*0.05) for i in y]
. If you use zip(y)
all the entries you iterate over will be tuples.
Upvotes: 1