🎉

自己相関係数を計算してみた

に公開

概要

自己相関係数を実際に計算しました。自己相関係数とはという方は、次を参照してください。

https://ja.wikipedia.org/wiki/自己相関#回帰分析における自己相関

実装

1、2、3、1、2、3

という数列に対して1から5ラグをずらして計算します。

module Mikumo
    using Statistics

    function autocorrelation_coefficient(xn::Array, h::Int)
        x_bar = mean(xn)
        x_length = length(xn)

        c0 =  xn .- x_bar |> x -> x .^2 |> sum |> x -> x / x_length
        ch = 0

        for i ∈ 1:x_length-h
            ch += (xn[i] - x_bar)*(xn[i+h] - x_bar)
        end

        ch = ch / x_length

        return ch / c0
    end
end
module TestMikumo
    using Test

    include("acf.jl")

    function main()
        @testset "autocorrelation_coefficient" begin
            xn = [1, 2, 3, 1, 2, 3]

            @test Mikumo.autocorrelation_coefficient(xn, 1) == -0.25
            @test Mikumo.autocorrelation_coefficient(xn, 2) == -0.5
            @test Mikumo.autocorrelation_coefficient(xn, 3) == 0.5
            @test Mikumo.autocorrelation_coefficient(xn, 4) == 0
            @test Mikumo.autocorrelation_coefficient(xn, 5) == -0.25
        end
    end
end

if abspath(PROGRAM_FILE) == @__FILE__
    using .TestMikumo

    TestMikumo.main()
end

Discussion