Install via yarn add locutus and import:
import { correlation } from 'locutus/python/statistics/correlation'.
Or with CommonJS: const { correlation } = require('locutus/python/statistics/correlation')
Use a bundler that supports tree-shaking so you only ship the functions you actually use.
Vite,
webpack,
Rollup, and
Parcel
all handle this. For server-side use this is less of a concern.
Examples
These examples are extracted from test cases that automatically verify our functions against their native counterparts.
#
code
expected result
1
correlation([1, 2, 3], [1, 5, 7])
0.9819805060619659
2
correlation([1, 2, 3], [7, 5, 3])
-1
3
correlation([1, 2, 3], [3, 2, 1], 'ranked')
-1
Notes
Returns Pearson correlation by default and supports Python’s ranked mode for Spearman correlation.
Dependencies
This function uses the following Locutus functions:
exportfunctioncorrelation(x: unknown, y: unknown, method: 'linear' | 'ranked' = 'linear'): number { // discuss at: https://locutus.io/python/statistics/correlation/ // parity verified: Python 3.12 // original by: Kevin van Zonneveld (https://kvz.io) // note 1: Returns Pearson correlation by default and supports Python's ranked mode for Spearman correlation. // example 1: correlation([1, 2, 3], [1, 5, 7]) // returns 1: 0.9819805060619659 // example 2: correlation([1, 2, 3], [7, 5, 3]) // returns 2: -1 // example 3: correlation([1, 2, 3], [3, 2, 1], 'ranked') // returns 3: -1
const left = assertStatisticsArray(x, 'correlation').map((value) =>toStatisticNumber(value, 'correlation')) const right = assertStatisticsArray(y, 'correlation').map((value) =>toStatisticNumber(value, 'correlation'))
const n = left.length if (right.length !== n) { thrownewError('correlation requires that both inputs have same number of data points') } if (n < 2) { thrownewError('correlation requires at least two data points') } if (method !== 'linear' && method !== 'ranked') { thrownewTypeError(`Unknown method: '${String(method)}'`) }
const sxy = sumProducts(xValues, yValues) const sxx = sumProducts(xValues, xValues) const syy = sumProducts(yValues, yValues) const denominator = Math.sqrt(sxx * syy) if (denominator === 0) { thrownewError('at least one of the inputs is constant') }
return sxy / denominator }
functioncenterValues(values: number[]): number[] { const mean = values.reduce((sum, value) => sum + value, 0) / values.length return values.map((value) => value - mean) }
exportfunctioncorrelation(x, y, method = 'linear') { // discuss at: https://locutus.io/python/statistics/correlation/ // parity verified: Python 3.12 // original by: Kevin van Zonneveld (https://kvz.io) // note 1: Returns Pearson correlation by default and supports Python's ranked mode for Spearman correlation. // example 1: correlation([1, 2, 3], [1, 5, 7]) // returns 1: 0.9819805060619659 // example 2: correlation([1, 2, 3], [7, 5, 3]) // returns 2: -1 // example 3: correlation([1, 2, 3], [3, 2, 1], 'ranked') // returns 3: -1
const left = assertStatisticsArray(x, 'correlation').map((value) =>toStatisticNumber(value, 'correlation')) const right = assertStatisticsArray(y, 'correlation').map((value) =>toStatisticNumber(value, 'correlation'))
const n = left.length if (right.length !== n) { thrownewError('correlation requires that both inputs have same number of data points') } if (n < 2) { thrownewError('correlation requires at least two data points') } if (method !== 'linear' && method !== 'ranked') { thrownewTypeError(`Unknown method: '${String(method)}'`) }
const sxy = sumProducts(xValues, yValues) const sxx = sumProducts(xValues, xValues) const syy = sumProducts(yValues, yValues) const denominator = Math.sqrt(sxx * syy) if (denominator === 0) { thrownewError('at least one of the inputs is constant') }
return sxy / denominator }
functioncenterValues(values) { const mean = values.reduce((sum, value) => sum + value, 0) / values.length return values.map((value) => value - mean) }
let position = 0 while (position < indexed.length) { let end = position + 1 while (end < indexed.length && indexed[end]?.value === indexed[position]?.value) { end += 1 } const averageRank = start + (position + end - 1) / 2 for (let cursor = position; cursor < end; cursor += 1) { const entry = indexed[cursor] if (entry) { ranks[entry.index] = averageRank } } position = end }
return ranks }
// python/_helpers/_statistics (Locutus helper dependency) functionassertStatisticsArray(data: unknown, functionName: string): unknown[] { if (!Array.isArray(data)) { thrownewTypeError(`${functionName}() data must be an array`) }
return data }
functiontoStatisticNumber(value: unknown, functionName: string): number { if (typeof value === 'number') { return value }
if (typeof value === 'boolean') { return value ? 1 : 0 }
if (typeof value === 'bigint') { const numericValue = Number(value) if (!Number.isSafeInteger(numericValue)) { thrownewRangeError(`${functionName}() bigint values must fit within JS safe integers`) }
return numericValue }
thrownewTypeError(`${functionName}() data must contain only real numbers`) }
functionsumProducts(left: number[], right: number[]): number { let total = 0 for (let index = 0; index < left.length; index += 1) { total += (left[index] ?? 0) * (right[index] ?? 0) } return total }
// python/statistics/correlation (target function module) functioncorrelation(x: unknown, y: unknown, method: 'linear' | 'ranked' = 'linear'): number { // discuss at: https://locutus.io/python/statistics/correlation/ // parity verified: Python 3.12 // original by: Kevin van Zonneveld (https://kvz.io) // note 1: Returns Pearson correlation by default and supports Python's ranked mode for Spearman correlation. // example 1: correlation([1, 2, 3], [1, 5, 7]) // returns 1: 0.9819805060619659 // example 2: correlation([1, 2, 3], [7, 5, 3]) // returns 2: -1 // example 3: correlation([1, 2, 3], [3, 2, 1], 'ranked') // returns 3: -1
const left = assertStatisticsArray(x, 'correlation').map((value) =>toStatisticNumber(value, 'correlation')) const right = assertStatisticsArray(y, 'correlation').map((value) =>toStatisticNumber(value, 'correlation'))
const n = left.length if (right.length !== n) { thrownewError('correlation requires that both inputs have same number of data points') } if (n < 2) { thrownewError('correlation requires at least two data points') } if (method !== 'linear' && method !== 'ranked') { thrownewTypeError(`Unknown method: '${String(method)}'`) }
const sxy = sumProducts(xValues, yValues) const sxx = sumProducts(xValues, xValues) const syy = sumProducts(yValues, yValues) const denominator = Math.sqrt(sxx * syy) if (denominator === 0) { thrownewError('at least one of the inputs is constant') }
return sxy / denominator }
functioncenterValues(values: number[]): number[] { const mean = values.reduce((sum, value) => sum + value, 0) / values.length return values.map((value) => value - mean) }
let position = 0 while (position < indexed.length) { let end = position + 1 while (end < indexed.length && indexed[end]?.value === indexed[position]?.value) { end += 1 } const averageRank = start + (position + end - 1) / 2 for (let cursor = position; cursor < end; cursor += 1) { const entry = indexed[cursor] if (entry) { ranks[entry.index] = averageRank } } position = end }
return ranks }
// python/_helpers/_statistics (Locutus helper dependency) functionassertStatisticsArray(data, functionName) { if (!Array.isArray(data)) { thrownewTypeError(`${functionName}() data must be an array`) }
return data }
functiontoStatisticNumber(value, functionName) { if (typeof value === 'number') { return value }
if (typeof value === 'boolean') { return value ? 1 : 0 }
if (typeof value === 'bigint') { const numericValue = Number(value) if (!Number.isSafeInteger(numericValue)) { thrownewRangeError(`${functionName}() bigint values must fit within JS safe integers`) }
return numericValue }
thrownewTypeError(`${functionName}() data must contain only real numbers`) }
functionsumProducts(left, right) { let total = 0 for (let index = 0; index < left.length; index += 1) { total += (left[index] ?? 0) * (right[index] ?? 0) } return total }
// python/statistics/correlation (target function module) functioncorrelation(x, y, method = 'linear') { // discuss at: https://locutus.io/python/statistics/correlation/ // parity verified: Python 3.12 // original by: Kevin van Zonneveld (https://kvz.io) // note 1: Returns Pearson correlation by default and supports Python's ranked mode for Spearman correlation. // example 1: correlation([1, 2, 3], [1, 5, 7]) // returns 1: 0.9819805060619659 // example 2: correlation([1, 2, 3], [7, 5, 3]) // returns 2: -1 // example 3: correlation([1, 2, 3], [3, 2, 1], 'ranked') // returns 3: -1
const left = assertStatisticsArray(x, 'correlation').map((value) =>toStatisticNumber(value, 'correlation')) const right = assertStatisticsArray(y, 'correlation').map((value) =>toStatisticNumber(value, 'correlation'))
const n = left.length if (right.length !== n) { thrownewError('correlation requires that both inputs have same number of data points') } if (n < 2) { thrownewError('correlation requires at least two data points') } if (method !== 'linear' && method !== 'ranked') { thrownewTypeError(`Unknown method: '${String(method)}'`) }
const sxy = sumProducts(xValues, yValues) const sxx = sumProducts(xValues, xValues) const syy = sumProducts(yValues, yValues) const denominator = Math.sqrt(sxx * syy) if (denominator === 0) { thrownewError('at least one of the inputs is constant') }
return sxy / denominator }
functioncenterValues(values) { const mean = values.reduce((sum, value) => sum + value, 0) / values.length return values.map((value) => value - mean) }
let position = 0 while (position < indexed.length) { let end = position + 1 while (end < indexed.length && indexed[end]?.value === indexed[position]?.value) { end += 1 } const averageRank = start + (position + end - 1) / 2 for (let cursor = position; cursor < end; cursor += 1) { const entry = indexed[cursor] if (entry) { ranks[entry.index] = averageRank } } position = end }
return ranks }
Improve this function
Locutus is a community effort following
The McDonald's Theory:
we ship first iterations, hoping others will improve them.
If you see something that could be better, we'd love your contribution.
Click "New file" in the appropriate folder
on GitHub.
This will fork the project to your account, directly add the file to it, and send a
Pull Request to us.
We will then review it. If it's useful to the project and in line with our
contributing guidelines
your work will become part of Locutus and you'll be automatically credited
in the authors
section accordingly.