# Golang : Find correlation coefficient example

Tags : golang math-sqrt correlation-coefficient

Below is an example of Golang code to find the strength of relation between two given variables or correlation coefficient. For financial analysis, it is useful in finding out if a variable has negative or positive correlation.

From investopedia.com:

A correlation of -1.0 shows a perfect negative correlation, while a correlation of 1.0 shows a perfect positive correlation. A correlation of 0.0 shows zero or no relationship between the movement of the two variables.

Here you go!

```
package main
import (
"fmt"
"math"
)
func main() {
X := []int{15, 18, 21, 24, 27}
Y := []int{25, 25, 27, 31, 32}
// Size of X array.
n := len(X)
// Get the strength of relation between two variables - X and Y
fmt.Println(correlationCoefficient(X, Y, n))
}
func correlationCoefficient(X []int, Y []int, n int) float64 {
sum_X := 0
sum_Y := 0
sum_XY := 0
squareSum_X := 0
squareSum_Y := 0
for i := 0; i < n; i++ {
// sum of elements of array X.
sum_X = sum_X + X[i]
// sum of elements of array Y.
sum_Y = sum_Y + Y[i]
// sum of X[i] * Y[i].
sum_XY = sum_XY + X[i]*Y[i]
// sum of square of array elements.
squareSum_X = squareSum_X + X[i]*X[i]
squareSum_Y = squareSum_Y + Y[i]*Y[i]
}
// use formula for calculating correlation
// coefficient.
corr := float64((n*sum_XY - sum_X*sum_Y)) /
(math.Sqrt(float64((n*squareSum_X - sum_X*sum_X) * (n*squareSum_Y - sum_Y*sum_Y))))
return corr
}
```

Output:

0.9534625892455922

References :

https://www.investopedia.com/terms/c/correlationcoefficient.asp

https://www.geeksforgeeks.org/program-find-correlation-coefficient

https://www.socketloop.com/tutorials/golang-convert-cast-int-to-float-example

#### See also : Golang : Calculate Relative Strength Index(RSI) example

Tags : golang math-sqrt correlation-coefficient

##### By Adam Ng(黃武俊)

IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.

#### Advertisement

#### Tutorials

+17.6k Golang : Display float in 2 decimal points and rounding up or down

+3.8k Golang : Determine if time variables have same calendar day

718 Java : Generate multiplication table example

+20.6k Golang : UDP client server read write example

+2.9k Golang : How to convert a number to words

+7.3k Golang : HTTP response JSON encoded data

+12.1k How to enable MariaDB/MySQL logs ?

+9.4k Golang : Encrypt and decrypt data with TripleDES

+8.1k Golang : Convert date format and separator yyyy-mm-dd to dd-mm-yyyy

+1.9k Golang : Check if password length meet the requirement

+2.9k Ubuntu : connect() to unix:/var/run/php5-fpm.sock failed (13: Permission denied) while connecting to upstream

+3k Golang : Convert source code to assembly language