Skip to content

Instantly share code, notes, and snippets.

@parthi2929
Created November 3, 2018 04:13
Show Gist options
  • Select an option

  • Save parthi2929/bf6ed8fc9afd611b5a0cfc1064b8b63f to your computer and use it in GitHub Desktop.

Select an option

Save parthi2929/bf6ed8fc9afd611b5a0cfc1064b8b63f to your computer and use it in GitHub Desktop.
A sample proof to show both general and deformed formula of Covariance give same result
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Test A"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The general covariance formula:\n",
"\n",
"$$\n",
"\\mathrm{Cov}(X,Y) = \\dfrac{\\sum\\limits_{i=1}^N(x_i - \\overline{x})(y_i - \\overline{y})}{N}\n",
"$$"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Let X=[1, 2, 3, 4, 5] and Y=[2, 1, 4, 3, 0]"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"ExecuteTime": {
"end_time": "2018-11-03T03:40:31.346008Z",
"start_time": "2018-11-03T03:40:31.332002Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"-0.4\n"
]
}
],
"source": [
"X, Y = [1,2,3,4,5], [2,1,4,3,0]\n",
"N = len(X) # or len(Y) also should do as both should be equal\n",
"Xb, Yb = sum(X)/len(X), sum(Y)/len(Y)\n",
" \n",
" # first formula\n",
"num = 0\n",
"for i in range(N):\n",
" num += (X[i] - Xb)*(Y[i] - Yb)\n",
"\n",
"cov1 = num/N\n",
"print(cov1)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Test B"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The deformed formula\n",
"\n",
"$$\n",
"\\mathrm{Cov}(X,Y) = \\dfrac{\\sum\\limits_{i=1}^N\\sum\\limits_{j=i+1}^N(x_i-x_j)(y_i - y_j)}{N^2}\n",
"$$"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"ExecuteTime": {
"end_time": "2018-11-03T04:11:30.734958Z",
"start_time": "2018-11-03T04:11:30.725961Z"
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"-0.4\n"
]
}
],
"source": [
"# second formula\n",
"num = 0\n",
"for i in range(0,N):\n",
" for j in range(i+1,N):\n",
" num += (X[i] - X[j])*(Y[i] - Y[j])\n",
"\n",
"cov2 = num/(N**2)\n",
"print(cov2)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python [conda env:Anaconda3]",
"language": "python",
"name": "conda-env-Anaconda3-py"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.6.4"
},
"toc": {
"base_numbering": 1,
"nav_menu": {},
"number_sections": true,
"sideBar": true,
"skip_h1_title": false,
"title_cell": "Table of Contents",
"title_sidebar": "Contents",
"toc_cell": false,
"toc_position": {},
"toc_section_display": true,
"toc_window_display": false
}
},
"nbformat": 4,
"nbformat_minor": 2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment