Loading...
Searching...
No Matches
prho.hpp
1// Copyright © 2020 Thomas Nagler
2//
3// This file is part of the wdm library and licensed under the terms of
4// the MIT license. For a copy, see the LICENSE file in the root directory
5// or https://github.com/tnagler/wdm/blob/master/LICENSE.
6
7#pragma once
8
9#include "utils.hpp"
10
11namespace wdm {
12
13namespace impl {
14
18inline double
19prho(std::vector<double> x,
20 std::vector<double> y,
21 std::vector<double> weights = std::vector<double>())
22{
23 utils::check_sizes(x, y, weights);
24 size_t n = x.size();
25 if (weights.size() == 0)
26 weights = std::vector<double>(x.size(), 1.0);
27
28 // calculate means of x and y
29 double mu_x = 0.0, mu_y = 0.0, w_sum = 0.0;
30 for (size_t i = 0; i < n; i++) {
31 mu_x += x[i] * weights[i];
32 mu_y += y[i] * weights[i];
33 w_sum += weights[i];
34 }
35 mu_x /= w_sum;
36 mu_y /= w_sum;
37
38 // substract mean from x and y
39 for (size_t i = 0; i < n; i++) {
40 x[i] -= mu_x;
41 y[i] -= mu_y;
42 }
43
44 // compute variances and covariance
45 double v_x = 0.0, v_y = 0.0, cov = 0.0;
46 for (size_t i = 0; i < n; i++) {
47 v_x += x[i] * x[i] * weights[i];
48 v_y += y[i] * y[i] * weights[i];
49 cov += x[i] * y[i] * weights[i];
50 }
51
52 // compute correlation
53 return cov / std::sqrt(v_x * v_y);
54}
55
56}
57
58}
Weighted dependence measures.
Definition wdm.hpp:19