A Free Sample of Autocorrelation
R, 3 31 25 bytes
# changes the builtin to only return the acf
body(acf)=body(acf)[1:18]
Usage (returns an array with the autocorrelations)
(acf(c(2.4, 2.4, 2.4, 2.2, 2.1, 1.5, 2.3, 2.3, 2.5, 2),5))
# , , 1
#
# [,1]
# [1,] 1.00000000
# [2,] 0.07659298
# [3,] -0.06007802
# [4,] -0.51144343
# [5,] -0.02912874
# [6,] -0.10468140
Background:
The 31 byte solution based on the original acf
built in
function(n,h)c(acf(n,h,,F)$acf)
Note that the 3 byte option acf
is the originalbuilt in that will plot (and print to 3 digits) while returning the required autocorrelation as an element in a list.
usage
acf(c(2.4, 2.4, 2.4, 2.2, 2.1, 1.5, 2.3, 2.3, 2.5, 2),5)
output:
# Autocorrelations of series ‘c(2.4, 2.4, 2.4, 2.2, 2.1, 1.5, 2.3, 2.3, 2.5, 2)’, by lag
#
# 0 1 2 3 4 5
# 1.000 0.077 -0.060 -0.511 -0.029 -0.105
If we want the correlations to display to more than 3 decimal places then 28 bytes will do it (or 31, if we want to suppress the plot)
# will still plot (28 bytes)
function(n,h)c(acf(n,h)$acf)
# won't plot (31 bytes)
function(n,h)c(acf(n,h,,F)$acf)
Jelly, 26 25 24 23 20 bytes
×L_SµḊ;0µƓС׹S€µF÷Ḣ
Try it online!
How it works
×L_SµḊ;0µƓС׹S€µF÷Ḣ Main link. Input: x (list) STDIN: h (integer)
×L Multiply all items in x by the length of x.
_S Subtract the sum of x from all products.
Let's call the result X.
µ Begin a new monadic chain. Argument: t (list)
Ḋ Remove the first element of t.
;0 Append a 0 to the result.
µ Push the previous chain and begin a new one.
Argument: X
Ɠ Read h from STDIN.
С Repeat the Ḋ;0 chain h times, collecting the h+1 intermediate
results in a list A.
×¹ Multiply the vectors in A by X.
S€ Compute the sum of each vectorized product.
µ Begin a new, monadic chain. Argument: S (sums)
F Flatten S. This does nothing except creating a deep copy.
Ḣ Pop the first element of S.
÷ Divide all elements of the copy by the first element.
Python 3, 147 130 126 120 bytes
def p(h,x):x=[t-sum(x)/len(x)for t in x];return[sum(s*t for s,t in zip(x[n:],x))/sum(b*b for b in x)for n in range(h+1)]
This solution is probably going to be golfed further, It's just a start.
You can call it with:
p(5,[2.4, 2.4, 2.4, 2.2, 2.1, 1.5, 2.3, 2.3, 2.5, 2])