Skip to content

Instantly share code, notes, and snippets.

@wrathematics
Created December 12, 2021 18:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wrathematics/f435af581f1f5dfd2e00f5ba71fe5e30 to your computer and use it in GitHub Desktop.
Save wrathematics/f435af581f1f5dfd2e00f5ba71fe5e30 to your computer and use it in GitHub Desktop.
Amusing bug. This computes the pearson correlation of 2 vectors correctly on a small test case if the omp pragma is present, and incorrectly if it is removed. Do you see why?
template <typename REAL>
REAL cor(const cpuvec<REAL> &x, const cpuvec<REAL> &y)
{
const len_t n = x.size();
if (n != y.size())
throw std::runtime_error("non-conformal arguments");
const REAL *x_d = x.data_ptr();
const REAL *y_d = y.data_ptr();
const REAL meanx = x.sum() / n;
const REAL meany = y.sum() / n;
REAL cp = 0, normx = 0, normy = 0;
#pragma omp parallel for reduction(+: cp, normx, normy)
for (len_t i=0; i<n; i++)
{
const REAL xi_mm = x_d[i] - meanx;
const REAL yi_mm = y_d[i] - meany;
cp = xi_mm * yi_mm;
normx += xi_mm * xi_mm;
normy += yi_mm * yi_mm;
}
return cp / sqrt(normx * normy);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment