diff --git a/.ipynb_checkpoints/Practica1_Probabilidad-checkpoint.ipynb b/.ipynb_checkpoints/Practica1_Probabilidad-checkpoint.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..4fabe95ad395d5ed19b21ed9e8ccc481c55a22c8 --- /dev/null +++ b/.ipynb_checkpoints/Practica1_Probabilidad-checkpoint.ipynb @@ -0,0 +1,309 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Introducción a la probabilidad\n", + "\n", + "**Autora**: Camila Rangel Smith (@crangelsmith en Github).\n", + "\n", + "**Nota**: Este notebook está basado en [esta página](https://www.dataquest.io/blog/basic-statistics-in-python-probability/) con modificaciones especÃficas para esta práctica. " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Probabilidad usando monedas\n", + "\n", + "La representación por excelencia de la probabilidad es el lanzamiento de una moneda. En un lanzamiento de moneda los únicos eventos que pueden ocurrir son:\n", + "\n", + "- Lanzar una cara\n", + "- Lanzar una cruz\n", + "\n", + "Estos dos sucesos forman el espacio muestral, el conjunto de todos los sucesos posibles que pueden ocurrir. \n", + "Para calcular la probabilidad de que ocurra un suceso, contamos cuántas veces puede ocurrir el suceso que nos interesa (por ejemplo, que salga cara) y lo dividimos entre el espacio muestral. \n", + "AsÃ, la probabilidad nos dirá que una moneda ideal tendrá una probabilidad de 1 entre 2 de salir cara o cruz. \n", + "Al observar los sucesos que pueden ocurrir, la probabilidad nos da un marco para hacer predicciones sobre la frecuencia con la que ocurrirán los sucesos. \n", + "Sin embargo, aunque parezca obvio, si realmente intentamos lanzar algunas monedas, es probable que de vez en cuando obtengamos un número anormalmente alto o bajo de caras. \n", + "Si no queremos hacer la suposición de que la moneda es justa, ¿qué podemos hacer? Podemos recopilar datos. Podemos utilizar la estadÃstica para calcular las probabilidades a \n", + "partir de las observaciones del mundo real y comprobar cómo se comparan con el ideal.\n", + "\n", + "## De la estadÃstica a la probabilidad\n", + "\n", + "Generaremos datos lanzando una moneda 10 veces y contando cuántas veces sale cara. Llamaremos ensayo a un conjunto de n lanzamientos de moneda (donde n es una variable que daremos). Nuestro dato será el número de caras que observemos. Puede que no obtengamos las 5 caras \"ideales\", pero no nos preocuparemos demasiado, ya que un ensayo es sólo un punto de datos. Si realizamos muchos, muchos ensayos, esperamos que el número medio de cabezas en todos nuestros ensayos se acerque al 50%. El código siguiente simula 10, 100, 1000 y 1000000 ensayos, y luego calcula la proporción media de cabezas observada. Nuestro proceso se resume también en la imagen de abajo.\n" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "import random\n", + "\n", + "def lanzar_moneda(n):\n", + " cara = 0\n", + " for i in range(n):\n", + " if random.random() <= 0.5:\n", + " cara +=1 \n", + " return cara/n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "La función `lanzar_moneda` es la que representa una simulación de 'n' lanzamientos de moneda.\n", + "Utiliza la función random() para generar un flotador entre 0 y 1, e incrementa nuestra cuenta de cabezas si está dentro de la mitad de ese rango. \n", + "La función regresa la división entre el numero de caras que ha obtenido, y el numero de veces que lanzamos la moneda. " + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Al lanzar la moneda 10 veces, la proporcion de vece que obtuvimos cara: 0.5\n", + "\n", + "Al lanzar la moneda 100 veces, la proporcion de vece que obtuvimos cara: 0.5\n", + "\n", + "Al lanzar la moneda 1000 veces, la proporcion de vece que obtuvimos cara: 0.517\n", + "\n", + "Al lanzar la moneda 1000000 veces, la proporcion de vece que obtuvimos cara: 0.499648\n" + ] + } + ], + "source": [ + "print ('Al lanzar la moneda 10 veces, la proporcion de vece que obtuvimos cara: ',lanzar_moneda(10))\n", + "print()\n", + "print ('Al lanzar la moneda 100 veces, la proporcion de vece que obtuvimos cara: ',lanzar_moneda(100))\n", + "print()\n", + "print ('Al lanzar la moneda 1000 veces, la proporcion de vece que obtuvimos cara: ',lanzar_moneda(1000))\n", + "print()\n", + "print ('Al lanzar la moneda 1000000 veces, la proporcion de vece que obtuvimos cara: ',lanzar_moneda(1000000))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "A continuación, la funcion `experimentos` repite estos ensayos de lanzar la moneda unas 100 veces el número de veces que queramos, devolviendo el número medio de cabezas en cada ensayo. " + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [], + "source": [ + "def experimentos(n,n_lanzamientos):\n", + " experimento = []\n", + " for i in range(n):\n", + " experimento.append(lanzar_moneda(n_lanzamientos))\n", + " return (experimento)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Las simulaciones de lanzamiento de monedas nos dan algunos resultados interesantes.\n", + "\n", + "En primer lugar, los datos confirman que nuestro número medio de caras se aproxima a lo que la probabilidad sugiere que deberÃa ser. Además, esta media mejora con más ensayos. En este ejemplo cada ensayo produce una única estimación de lo que la probabilidad sugiere que deberÃa ocurrir. La llamamos estimación porque sabemos que no será perfecta (es decir, no obtendremos 50% caras todas las veces)." + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Con 10 experimentos, valor medio: 0.5 desviación estandar: 0.1247219128924647\n", + "\n", + "Con 100 experimentos, valor medio: 0.506 desviación estandar: 0.14129273287623947\n", + "\n", + "Con 1000 experimentos, valor medio: 0.5046 desviación estandar: 0.16007643319509735\n", + "\n", + "Con 100000 experimentos, valor medio: 0.500633 desviación estandar: 0.15795932648149721\n" + ] + }, + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAAagAAAEYCAYAAAAJeGK1AAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjMuNCwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy8QVMy6AAAACXBIWXMAAAsTAAALEwEAmpwYAAAWj0lEQVR4nO3df6zldX3n8edLkNVusUJnnBAG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1MhDwAPA5Y3UtRX4Sjew7gMumvTv3np4tDq+RqltTl/HWMNjzEsdSZKaNK3HoCRJa5wBJUlqkgElSWqSASVJapIBJUlqkgElSWqSASVJatL/BzdXSMgge6kBAAAAAElFTkSuQmCC\n", + "text/plain": [ + "<Figure size 432x288 with 4 Axes>" + ] + }, + "metadata": { + "needs_background": "light" + }, + "output_type": "display_data" + } + ], + "source": [ + "import matplotlib.pyplot as plt\n", + "from statistics import mean, stdev \n", + "\n", + "n_lanzamientos = 10\n", + "\n", + "ex_10 = experimentos(10, n_lanzamientos)\n", + "ex_100 = experimentos(100, n_lanzamientos)\n", + "ex_1000 = experimentos(1000, n_lanzamientos)\n", + "ex_100000 = experimentos(100000, n_lanzamientos)\n", + "\n", + "\n", + "n_bins = 100\n", + "fig, axs = plt.subplots(2, 2, tight_layout=True)\n", + "axs[0,0].hist(ex_10, bins=n_bins, range=[0.1,0.9] )\n", + "axs[0,1].hist(ex_100, bins=n_bins, range=[0.1,0.9])\n", + "axs[1,0].hist(ex_1000, bins=n_bins, range=[0.1,0.9])\n", + "axs[1,1].hist(ex_100000, bins=n_bins, range=[0.1,0.9])\n", + "\n", + "print ('Con 10 experimentos, valor medio:',mean(ex_10), 'desviación estandar:', stdev(ex_10))\n", + "print()\n", + "print ('Con 100 experimentos, valor medio:',mean(ex_100), 'desviación estandar:', stdev(ex_100))\n", + "print()\n", + "print ('Con 1000 experimentos, valor medio:',mean(ex_1000), 'desviación estandar:', stdev(ex_1000))\n", + "print()\n", + "print ('Con 100000 experimentos, valor medio:',mean(ex_100000), 'desviación estandar:', stdev(ex_100000))\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "En 10 ensayos, hay un ligero error, pero este error desaparece casi por completo con 1.000.000 experimentos. \n", + "\n", + "A medida que tenemos más ensayos, la desviación de la media disminuye. Seguro que podrÃamos haber lanzado la moneda nosotros mismos, pero Python nos ahorra mucho tiempo al permitirnos modelar este proceso en código. A medida que obtenemos más y más datos, el mundo real empieza a parecerse al ideal." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Preguntas\n", + "\n", + "- ¿Qué distribución obserbamos en las estimaciones de estos experimentos? ¿Cual es la razón de que todos sigan esta distribución?\n", + "- A medida que tenemos más ensayos, la desviación de la media con respecto al valor real disminuye. ¿Qué pasa con la desviación estandar?\n", + "- ¿Cómo se veria una figura que grafique el valor medio y desviación estandar como función del numero de ensayos?\n", + "- ¿Como simulamos una monda trucada?\n", + "- ¿Como simulamos el resultado de lanzar dos monedas? E.g probabilidad de tener dos caras." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Ensayos de Bernulli\n", + "\n", + "Lanzar una moneda tiene dos resultados posibles. Este sencillo experimento, denominado ensayo de Bernoulli, se modela mediante una variable aleatoria denominada Bernoulli. Entender este bloque de construcción nos puede llevar lejos. Podemos utilizarlo para construir modelos más complejos.\n", + "\n", + "Python tiene su propia librerias para simular ensayos de Bernulli dato un numero de lanzamientos y una probabilidad. \n", + "Para obtener el resultado de 15 ensayos Bernoulli con una probabilidad de éxito igual a 0,5 (una moneda justa), escribimos\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "array([1, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0])" + ] + }, + "execution_count": 5, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "from scipy.stats import bernoulli\n", + "bernoulli.rvs(size=15,p=0.5)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Ejercicios" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Los siguientes ejercicios deben ser realizados durante la sesión practica. Lo ideal seria hacer el calculo de la probabilidad, simular los experimentos y comparar los resultados. Para las simulaciones podemos usar las funciones definidas antes e implementar algunas modificaciones.\n", + "\n", + "Los ejercicios están basados en el siguiente escenario:\n", + "\n", + "*Tenemos 3 monedas en una bolsa, una moneda está trucada (99% de probabilidad de salir sello al lanzarse), las otras dos son monedas normales.*\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "1. El experimento consiste en alatoreamente sacar una moneda de la bolsa, lanzarla, anotar el resultado y volver a introducir la moneda en la bolsa. Repites esta acción hasta haber lanzado monedas unas 21 veces. Preguntas:\n", + "\n", + " - Estimar cuantas caras esperas obtener al terminar el experimento. \n", + " - Simular 100 experimentos para estimar cuantas caras esperas obtener en un experimento. \n", + " - Estimar qué desviación esperas entre experimento y experimento. " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "2. El experimento consiste en alatoreamente sacar una moneda de la bolsa, lanzarla, y luego sacar las dos monedas que quedan en la bolsa, lanzarlas y anotar los resultado\n", + " Repites esta acción hasta haber lanzado monedas unas 21 veces. Preguntas:\n", + "\n", + " - ¿En qué sentido este ejemplo es distinto a 1?\n", + " - Simular 100 experimentos para estimar cuantas caras esperas obtener en un experimento. \n", + " - Estimar qué desviación esperas entre experimento y experimento. " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "3. Sacamos la primera moneda. \n", + " - ¿Cual es la probabilidad que sea una moneda truncada? \n", + " - Ahora la lanzamos y nos sale sello. Con esta información, ¿cual es la probabilidad que sea una moneda truncada? \n", + " " + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "clase13datos", + "language": "python", + "name": "clase13datos" + }, + "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.7.3" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/.ipynb_checkpoints/solutions-checkpoint.ipynb b/.ipynb_checkpoints/solutions-checkpoint.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..384461da436c6a5e61f6ffa34463caf2052383d9 --- /dev/null +++ b/.ipynb_checkpoints/solutions-checkpoint.ipynb @@ -0,0 +1,1075 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Ejercicios\n", + "\n", + "*Tenemos 3 monedas en una bolsa, una moneda está trucada (99% de probabilidad de salir sello al lanzarse), las otras dos son monedas normales.*\n", + "\n", + "1. El experimento consiste en alatoreamente sacar una moneda de la bolsa, lanzarla, anotar el resultado y volver a introducir la moneda en la bolsa. Repites esta acción hasta haber lanzado monedas unas 21 veces. Preguntas:\n", + "\n", + " - Estimar cuantas caras esperas obtener al terminar el experimento. \n", + " - Simular 100 experimentos para estimar cuantas caras esperas obtener en un experimento. \n", + " - Estimar qué desviación esperas entre experimento y experimento. " + ] + }, + { + "cell_type": "code", + "execution_count": 32, + "metadata": {}, + "outputs": [], + "source": [ + "import random\n" + ] + }, + { + "cell_type": "code", + "execution_count": 147, + "metadata": {}, + "outputs": [], + "source": [ + "Sello = \"Sello\"\n", + "Cara = \"Cara\"\n", + "def flipCoin1():\n", + " choice = random.choice([True,False])\n", + " if choice == True:\n", + " choice = Cara\n", + " else:\n", + " choice = Sello\n", + " return choice\n", + "\n", + "\n", + "def flipCoin2():\n", + " choice = random.choice([True,False,True,True,True,True,True,True,True,True])\n", + " if choice == True:\n", + " choice = Sello\n", + " else:\n", + " choice = Cara\n", + " return choice" + ] + }, + { + "cell_type": "code", + "execution_count": 68, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'Sello'" + ] + }, + "execution_count": 68, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "flipCoin2()" + ] + }, + { + "cell_type": "code", + "execution_count": 148, + "metadata": {}, + "outputs": [], + "source": [ + "moneda = []\n", + "def sacamonedas(n):\n", + " sellos = 0\n", + " p = 0\n", + " q = 0\n", + " for i in range(0,n,1):\n", + " value = random.randint(0, 3)\n", + " if value == 0:\n", + " tmp = flipCoin2()\n", + " moneda.append(tmp)\n", + " if tmp == \"Sello\":\n", + " sellos +=1\n", + " else:\n", + " tmp = flipCoin1()\n", + " moneda.append(tmp) \n", + " if tmp == \"Sello\":\n", + " sellos +=1\n", + " p = sellos/n\n", + " q = 1-p\n", + " return moneda, sellos, p, q" + ] + }, + { + "cell_type": "code", + "execution_count": 149, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "(['Cara',\n", + " 'Sello',\n", + " 'Cara',\n", + " 'Sello',\n", + " 'Sello',\n", + " 'Sello',\n", + " 'Cara',\n", + " 'Cara',\n", + " 'Sello',\n", + " 'Cara',\n", + " 'Sello',\n", + " 'Sello',\n", + " 'Sello',\n", + " 'Sello',\n", + " 'Sello',\n", + " 'Sello',\n", + " 'Cara',\n", + " 'Sello',\n", + " 'Cara',\n", + " 'Sello',\n", + " 'Sello',\n", + " 'Sello',\n", + " 'Sello',\n", + " 'Sello',\n", + " 'Cara',\n", + " 'Cara',\n", + " 'Sello',\n", + " 'Sello',\n", + " 'Cara',\n", + " 'Sello',\n", + " 'Sello',\n", + " 'Cara',\n", + " 'Sello',\n", + " 'Sello',\n", + " 'Sello',\n", + " 'Cara',\n", + " 'Sello',\n", + " 'Cara',\n", + " 'Sello',\n", + " 'Cara',\n", + " 'Sello',\n", + " 'Sello',\n", + " 'Cara',\n", + " 'Sello',\n", + " 'Cara',\n", + " 'Sello',\n", + " 'Cara',\n", + " 'Cara',\n", + " 'Cara',\n", + " 'Cara',\n", + " 'Cara',\n", + " 'Cara',\n", + " 'Sello',\n", + " 'Cara',\n", + " 'Sello',\n", + " 'Sello',\n", + " 'Sello',\n", + " 'Sello',\n", + " 'Cara',\n", + " 'Sello',\n", + " 'Cara',\n", + " 'Cara',\n", + " 'Cara',\n", + " 'Sello',\n", + " 'Sello',\n", + " 'Sello',\n", + " 'Sello',\n", + " 'Sello',\n", + " 'Cara',\n", + " 'Sello',\n", + " 'Sello',\n", + " 'Cara',\n", + " 'Cara',\n", + " 'Sello',\n", + " 'Sello',\n", + " 'Sello',\n", + " 'Sello',\n", + " 'Cara',\n", + " 'Cara',\n", + " 'Cara',\n", + " 'Cara',\n", + " 'Sello',\n", + " 'Cara',\n", + " 'Sello',\n", + " 'Sello',\n", + " 'Sello',\n", + " 'Sello',\n", + " 'Sello',\n", + " 'Sello',\n", + " 'Cara',\n", + " 'Sello',\n", + " 'Sello',\n", + " 'Sello',\n", + " 'Sello',\n", + " 'Sello',\n", + " 'Sello',\n", + " 'Cara',\n", + " 'Cara',\n", + " 'Sello',\n", + " 'Sello'],\n", + " 62,\n", + " 0.62,\n", + " 0.38)" + ] + }, + "execution_count": 149, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "sacamonedas(100)" + ] + }, + { + "cell_type": "code", + "execution_count": 132, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "(array([61., 0., 0., 0., 0., 0., 0., 0., 0., 39.]),\n", + " array([0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1. ]),\n", + " <BarContainer object of 10 artists>)" + ] + }, + "execution_count": 132, + "metadata": {}, + "output_type": "execute_result" + }, + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAAXAAAAD4CAYAAAD1jb0+AAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjMuNCwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy8QVMy6AAAACXBIWXMAAAsTAAALEwEAmpwYAAAM/klEQVR4nO3df6zd9V3H8efLXhCzuXXY67UC2SVZZWHL+HXBkSkTcAuOxXYJaUYW02iT/jPNjC6uc/+4ZBr4Q8dc3EwDyDVBAVHWZphtpNIZjbLdjp+lY3SkDcWWXrToWCJb4e0f51u9uT235/Tee+7Nxz0fCTnn++t835c/nv3223POTVUhSWrPj632AJKkxTHgktQoAy5JjTLgktQoAy5JjRpbyZOtW7euJicnV/KUktS8vXv3vlRV4/PXr2jAJycnmZmZWclTSlLzkhzqt95bKJLUKAMuSY0y4JLUKAMuSY0y4JLUKAMuSY0y4JLUKAMuSY0y4JLUqKE+iZlkLXA78E6gg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NowkrZKR9CtVNYrXlSSNmJ/ElKRGGXBJatSqBzzJp5LsS/JEkseSnPJe8jn73pXkpu75niS+rVDSqknyM0nuSfLdJHuT/H2Sn1up84/8feCnk+Rq4IPA5VX1apJ1wNmrOZMkDSNJgAeA6ar6cLfuEmAC+M4Qx6aqXl/KDKt9Bb4eeKmqXgWoqpeq6t+SXJHk692faF9Nsv50L5Lk5iRPJnkq8bOTklbEtcAPq+rPT66oqseBR5PsTvKtrksbAZJMdl/+95fAU8AFSb6YZKa7C/HpMx1gtQP+NXo/xHeSfCHJe5OcBXweuKmqrgDuBP5woRdI8rPArcB1wKXAlUk2jXxyST/q3gns7bP+v4EPVdXl9CL/x90VN8AG4AtV9Y6qOgR8qvuE5ruA9yZ515kMsKq3UKrqlSRXAL9I7we9F/gMvf8xD3U/8xrgyGle5kpgT1XNAiS5G7gG+NLoJpekBQX4oyTXAK/T+96oiW7boar61zn7bu6+L2qM3h2Ji4Enhj3RqgYcoKpeA/YAe5I8CXwU2FdVV6/qYJJ0evuAm/qs/wgwDlxRVT9MchA4p9v2/ZM7JbkQ+DhwZVUdT3LXnP2Gsqq3UJJclGTDnFWXAvuB8e4fOElyVpJ3nOZlvkHvrx7ruu8ovxn4+qhmlqTOPwA/3l1BA9DdAnkrcKyL97Us8E2CwJvoBf0/k0zQ+90KZ2S1r8DfCHw+yVrgBHCA3lfP7gD+NMmb6c14G70/7U5RVUe63wb0ML2/ujxYVTtHP7qkH2VVVUk+BNyW5BP07n0fBP6AXr+eBGaAby9w/ONJHu22Pw/885nO4EfpJalRq/0uFEnSIhlwSWqUAZekRhlwSWqUAZekRhlwSWqUAZekRv0P+STaYw2wR50AAAAASUVORK5CYII=\n", + "text/plain": [ + "<Figure size 432x288 with 1 Axes>" + ] + }, + "metadata": { + "needs_background": "light" + }, + "output_type": "display_data" + } + ], + "source": [ + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "\n", + "plt.hist(moneda)" + ] + }, + { + "cell_type": "code", + "execution_count": 106, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Al lanzar la moneda 10000 veces, la proporcion de vece que obtuvimos Sello: 0.5978\n", + "Al lanzar la moneda 10000 veces, la proporcion de vece que obtuvimos Cara: 0.4022\n", + "\n" + ] + } + ], + "source": [ + "print ('Al lanzar la moneda 10000 veces, la proporcion de vece que obtuvimos Sello: ',prob)\n", + "q = 1-prob\n", + "print ('Al lanzar la moneda 10000 veces, la proporcion de vece que obtuvimos Cara: ',q)\n", + "print()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Lo que se hace acá es hacer el experimento n veces para tener una estadÃstica...\n", + "\n", + "def experimentos(n,n_lanzamientos):\n", + " experimento = []\n", + " for i in range(n):\n", + " experimento.append(lanzar_moneda(n_lanzamientos))\n", + " return (experimento)" + ] + }, + { + "cell_type": "code", + "execution_count": 107, + "metadata": {}, + "outputs": [ + { + "ename": "TypeError", + "evalue": "'int' object is not iterable", + "output_type": "error", + "traceback": [ + "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", + "\u001b[0;32m<ipython-input-107-1d5e300857b9>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[0;32mfrom\u001b[0m \u001b[0mstatistics\u001b[0m \u001b[0;32mimport\u001b[0m \u001b[0mmean\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mstdev\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 3\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 4\u001b[0;31m \u001b[0mprint\u001b[0m \u001b[0;34m(\u001b[0m\u001b[0;34m'Con 10000 experimentos, valor medio:'\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0mmean\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0msellos\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m'desviación estandar:'\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mstdev\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0msellos\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 5\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", + "\u001b[0;32m~/.conda/envs/clase13datos/lib/python3.7/statistics.py\u001b[0m in \u001b[0;36mmean\u001b[0;34m(data)\u001b[0m\n\u001b[1;32m 304\u001b[0m \u001b[0mIf\u001b[0m\u001b[0;31m \u001b[0m\u001b[0;31m`\u001b[0m\u001b[0;31m`\u001b[0m\u001b[0mdata\u001b[0m\u001b[0;31m`\u001b[0m\u001b[0;31m`\u001b[0m \u001b[0;32mis\u001b[0m \u001b[0mempty\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mStatisticsError\u001b[0m \u001b[0mwill\u001b[0m \u001b[0mbe\u001b[0m \u001b[0mraised\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 305\u001b[0m \"\"\"\n\u001b[0;32m--> 306\u001b[0;31m \u001b[0;32mif\u001b[0m \u001b[0miter\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mdata\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;32mis\u001b[0m \u001b[0mdata\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 307\u001b[0m \u001b[0mdata\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mlist\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mdata\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 308\u001b[0m \u001b[0mn\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mlen\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mdata\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", + "\u001b[0;31mTypeError\u001b[0m: 'int' object is not iterable" + ] + } + ], + "source": [ + "import matplotlib.pyplot as plt\n", + "from statistics import mean, stdev \n", + "\n", + "print ('Con 10000 experimentos, valor medio:',mean(sellos), 'desviación estandar:', stdev(sellos))\n", + "print()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "code", + "execution_count": 21, + "metadata": {}, + "outputs": [], + "source": [ + "\n", + "moneda = []\n", + "\n", + "choice = random.randint(0, 3)\n", + "\n", + "\n", + "def lanzar_truncada():\n", + " sello = 0\n", + " for i in range(n):\n", + " if random.random() <= 0.9:\n", + " sello +=1 \n", + " return sello/n\n", + "\n", + "def lanzar_moneda(n):\n", + " sello = 0\n", + " for i in range(n):\n", + " if random.random() <= 0.5:\n", + " sello +=1 \n", + " return sello/n" + ] + }, + { + "cell_type": "code", + "execution_count": 31, + "metadata": {}, + "outputs": [], + "source": [ + "monedas= []\n", + "tipo_moneda =0\n", + "def moneda(n):\n", + " for i in range(n):\n", + " tipo_moneda = random.random()\n", + " if tipo_moneda <= 0.33:\n", + " valor = lanzar_truncada(1)\n", + " monedas.append(valor)\n", + " else:\n", + " valor = lanzar_moneda(1)\n", + " monedas.append(valor)\n", + " print(monedas)\n" + ] + }, + { + "cell_type": "code", + "execution_count": 32, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[1.0, 0.0, 1.0, 1.0, 0.0, 1.0]\n" + ] + } + ], + "source": [ + "moneda(6)" + ] + }, + { + "cell_type": "code", + "execution_count": 30, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Help on module random:\n", + "\n", + "NAME\n", + " random - Random variable generators.\n", + "\n", + "MODULE REFERENCE\n", + " https://docs.python.org/3.7/library/random\n", + " \n", + " The following documentation is automatically generated from the Python\n", + " source files. It may be incomplete, incorrect or include features that\n", + " are considered implementation detail and may vary between Python\n", + " implementations. When in doubt, consult the module reference at the\n", + " location listed above.\n", + "\n", + "DESCRIPTION\n", + " integers\n", + " --------\n", + " uniform within range\n", + " \n", + " sequences\n", + " ---------\n", + " pick random element\n", + " pick random sample\n", + " pick weighted random sample\n", + " generate random permutation\n", + " \n", + " distributions on the real line:\n", + " ------------------------------\n", + " uniform\n", + " triangular\n", + " normal (Gaussian)\n", + " lognormal\n", + " negative exponential\n", + " gamma\n", + " beta\n", + " pareto\n", + " Weibull\n", + " \n", + " distributions on the circle (angles 0 to 2pi)\n", + " ---------------------------------------------\n", + " circular uniform\n", + " von Mises\n", + " \n", + " General notes on the underlying Mersenne Twister core generator:\n", + " \n", + " * The period is 2**19937-1.\n", + " * It is one of the most extensively tested generators in existence.\n", + " * The random() method is implemented in C, executes in a single Python step,\n", + " and is, therefore, threadsafe.\n", + "\n", + "CLASSES\n", + " _random.Random(builtins.object)\n", + " Random\n", + " SystemRandom\n", + " \n", + " class Random(_random.Random)\n", + " | Random(x=None)\n", + " | \n", + " | Random number generator base class used by bound module functions.\n", + " | \n", + " | Used to instantiate instances of Random to get generators that don't\n", + " | share state.\n", + " | \n", + " | Class Random can also be subclassed if you want to use a different basic\n", + " | generator of your own devising: in that case, override the following\n", + " | methods: random(), seed(), getstate(), and setstate().\n", + " | Optionally, implement a getrandbits() method so that randrange()\n", + " | can cover arbitrarily large ranges.\n", + " | \n", + " | Method resolution order:\n", + " | Random\n", + " | _random.Random\n", + " | builtins.object\n", + " | \n", + " | Methods defined here:\n", + " | \n", + " | __getstate__(self)\n", + " | # Issue 17489: Since __reduce__ was defined to fix #759889 this is no\n", + " | # longer called; we leave it here because it has been here since random was\n", + " | # rewritten back in 2001 and why risk breaking something.\n", + " | \n", + " | __init__(self, x=None)\n", + " | Initialize an instance.\n", + " | \n", + " | Optional argument x controls seeding, as for Random.seed().\n", + " | \n", + " | __reduce__(self)\n", + " | Helper for pickle.\n", + " | \n", + " | __setstate__(self, state)\n", + " | \n", + " | betavariate(self, alpha, beta)\n", + " | Beta distribution.\n", + " | \n", + " | Conditions on the parameters are alpha > 0 and beta > 0.\n", + " | Returned values range between 0 and 1.\n", + " | \n", + " | choice(self, seq)\n", + " | Choose a random element from a non-empty sequence.\n", + " | \n", + " | choices(self, population, weights=None, *, cum_weights=None, k=1)\n", + " | Return a k sized list of population elements chosen with replacement.\n", + " | \n", + " | If the relative weights or cumulative weights are not specified,\n", + " | the selections are made with equal probability.\n", + " | \n", + " | expovariate(self, lambd)\n", + " | Exponential distribution.\n", + " | \n", + " | lambd is 1.0 divided by the desired mean. It should be\n", + " | nonzero. (The parameter would be called \"lambda\", but that is\n", + " | a reserved word in Python.) Returned values range from 0 to\n", + " | positive infinity if lambd is positive, and from negative\n", + " | infinity to 0 if lambd is negative.\n", + " | \n", + " | gammavariate(self, alpha, beta)\n", + " | Gamma distribution. Not the gamma function!\n", + " | \n", + " | Conditions on the parameters are alpha > 0 and beta > 0.\n", + " | \n", + " | The probability distribution function is:\n", + " | \n", + " | x ** (alpha - 1) * math.exp(-x / beta)\n", + " | pdf(x) = --------------------------------------\n", + " | math.gamma(alpha) * beta ** alpha\n", + " | \n", + " | gauss(self, mu, sigma)\n", + " | Gaussian distribution.\n", + " | \n", + " | mu is the mean, and sigma is the standard deviation. This is\n", + " | slightly faster than the normalvariate() function.\n", + " | \n", + " | Not thread-safe without a lock around calls.\n", + " | \n", + " | getstate(self)\n", + " | Return internal state; can be passed to setstate() later.\n", + " | \n", + " | lognormvariate(self, mu, sigma)\n", + " | Log normal distribution.\n", + " | \n", + " | If you take the natural logarithm of this distribution, you'll get a\n", + " | normal distribution with mean mu and standard deviation sigma.\n", + " | mu can have any value, and sigma must be greater than zero.\n", + " | \n", + " | normalvariate(self, mu, sigma)\n", + " | Normal distribution.\n", + " | \n", + " | mu is the mean, and sigma is the standard deviation.\n", + " | \n", + " | paretovariate(self, alpha)\n", + " | Pareto distribution. alpha is the shape parameter.\n", + " | \n", + " | randint(self, a, b)\n", + " | Return random integer in range [a, b], including both end points.\n", + " | \n", + " | randrange(self, start, stop=None, step=1, _int=<class 'int'>)\n", + " | Choose a random item from range(start, stop[, step]).\n", + " | \n", + " | This fixes the problem with randint() which includes the\n", + " | endpoint; in Python this is usually not what you want.\n", + " | \n", + " | sample(self, population, k)\n", + " | Chooses k unique random elements from a population sequence or set.\n", + " | \n", + " | Returns a new list containing elements from the population while\n", + " | leaving the original population unchanged. The resulting list is\n", + " | in selection order so that all sub-slices will also be valid random\n", + " | samples. This allows raffle winners (the sample) to be partitioned\n", + " | into grand prize and second place winners (the subslices).\n", + " | \n", + " | Members of the population need not be hashable or unique. If the\n", + " | population contains repeats, then each occurrence is a possible\n", + " | selection in the sample.\n", + " | \n", + " | To choose a sample in a range of integers, use range as an argument.\n", + " | This is especially fast and space efficient for sampling from a\n", + " | large population: sample(range(10000000), 60)\n", + " | \n", + " | seed(self, a=None, version=2)\n", + " | Initialize internal state from hashable object.\n", + " | \n", + " | None or no argument seeds from current time or from an operating\n", + " | system specific randomness source if available.\n", + " | \n", + " | If *a* is an int, all bits are used.\n", + " | \n", + " | For version 2 (the default), all of the bits are used if *a* is a str,\n", + " | bytes, or bytearray. For version 1 (provided for reproducing random\n", + " | sequences from older versions of Python), the algorithm for str and\n", + " | bytes generates a narrower range of seeds.\n", + " | \n", + " | setstate(self, state)\n", + " | Restore internal state from object returned by getstate().\n", + " | \n", + " | shuffle(self, x, random=None)\n", + " | Shuffle list x in place, and return None.\n", + " | \n", + " | Optional argument random is a 0-argument function returning a\n", + " | random float in [0.0, 1.0); if it is the default None, the\n", + " | standard random.random will be used.\n", + " | \n", + " | triangular(self, low=0.0, high=1.0, mode=None)\n", + " | Triangular distribution.\n", + " | \n", + " | Continuous distribution bounded by given lower and upper limits,\n", + " | and having a given mode value in-between.\n", + " | \n", + " | http://en.wikipedia.org/wiki/Triangular_distribution\n", + " | \n", + " | uniform(self, a, b)\n", + " | Get a random number in the range [a, b) or [a, b] depending on rounding.\n", + " | \n", + " | vonmisesvariate(self, mu, kappa)\n", + " | Circular data distribution.\n", + " | \n", + " | mu is the mean angle, expressed in radians between 0 and 2*pi, and\n", + " | kappa is the concentration parameter, which must be greater than or\n", + " | equal to zero. If kappa is equal to zero, this distribution reduces\n", + " | to a uniform random angle over the range 0 to 2*pi.\n", + " | \n", + " | weibullvariate(self, alpha, beta)\n", + " | Weibull distribution.\n", + " | \n", + " | alpha is the scale parameter and beta is the shape parameter.\n", + " | \n", + " | ----------------------------------------------------------------------\n", + " | Data descriptors defined here:\n", + " | \n", + " | __dict__\n", + " | dictionary for instance variables (if defined)\n", + " | \n", + " | __weakref__\n", + " | list of weak references to the object (if defined)\n", + " | \n", + " | ----------------------------------------------------------------------\n", + " | Data and other attributes defined here:\n", + " | \n", + " | VERSION = 3\n", + " | \n", + " | ----------------------------------------------------------------------\n", + " | Methods inherited from _random.Random:\n", + " | \n", + " | __getattribute__(self, name, /)\n", + " | Return getattr(self, name).\n", + " | \n", + " | getrandbits(...)\n", + " | getrandbits(k) -> x. Generates an int with k random bits.\n", + " | \n", + " | random(...)\n", + " | random() -> x in the interval [0, 1).\n", + " | \n", + " | ----------------------------------------------------------------------\n", + " | Static methods inherited from _random.Random:\n", + " | \n", + " | __new__(*args, **kwargs) from builtins.type\n", + " | Create and return a new object. See help(type) for accurate signature.\n", + " \n", + " class SystemRandom(Random)\n", + " | SystemRandom(x=None)\n", + " | \n", + " | Alternate random number generator using sources provided\n", + " | by the operating system (such as /dev/urandom on Unix or\n", + " | CryptGenRandom on Windows).\n", + " | \n", + " | Not available on all systems (see os.urandom() for details).\n", + " | \n", + " | Method resolution order:\n", + " | SystemRandom\n", + " | Random\n", + " | _random.Random\n", + " | builtins.object\n", + " | \n", + " | Methods defined here:\n", + " | \n", + " | getrandbits(self, k)\n", + " | getrandbits(k) -> x. Generates an int with k random bits.\n", + " | \n", + " | getstate = _notimplemented(self, *args, **kwds)\n", + " | \n", + " | random(self)\n", + " | Get the next random number in the range [0.0, 1.0).\n", + " | \n", + " | seed(self, *args, **kwds)\n", + " | Stub method. Not used for a system random number generator.\n", + " | \n", + " | setstate = _notimplemented(self, *args, **kwds)\n", + " | \n", + " | ----------------------------------------------------------------------\n", + " | Methods inherited from Random:\n", + " | \n", + " | __getstate__(self)\n", + " | # Issue 17489: Since __reduce__ was defined to fix #759889 this is no\n", + " | # longer called; we leave it here because it has been here since random was\n", + " | # rewritten back in 2001 and why risk breaking something.\n", + " | \n", + " | __init__(self, x=None)\n", + " | Initialize an instance.\n", + " | \n", + " | Optional argument x controls seeding, as for Random.seed().\n", + " | \n", + " | __reduce__(self)\n", + " | Helper for pickle.\n", + " | \n", + " | __setstate__(self, state)\n", + " | \n", + " | betavariate(self, alpha, beta)\n", + " | Beta distribution.\n", + " | \n", + " | Conditions on the parameters are alpha > 0 and beta > 0.\n", + " | Returned values range between 0 and 1.\n", + " | \n", + " | choice(self, seq)\n", + " | Choose a random element from a non-empty sequence.\n", + " | \n", + " | choices(self, population, weights=None, *, cum_weights=None, k=1)\n", + " | Return a k sized list of population elements chosen with replacement.\n", + " | \n", + " | If the relative weights or cumulative weights are not specified,\n", + " | the selections are made with equal probability.\n", + " | \n", + " | expovariate(self, lambd)\n", + " | Exponential distribution.\n", + " | \n", + " | lambd is 1.0 divided by the desired mean. It should be\n", + " | nonzero. (The parameter would be called \"lambda\", but that is\n", + " | a reserved word in Python.) Returned values range from 0 to\n", + " | positive infinity if lambd is positive, and from negative\n", + " | infinity to 0 if lambd is negative.\n", + " | \n", + " | gammavariate(self, alpha, beta)\n", + " | Gamma distribution. Not the gamma function!\n", + " | \n", + " | Conditions on the parameters are alpha > 0 and beta > 0.\n", + " | \n", + " | The probability distribution function is:\n", + " | \n", + " | x ** (alpha - 1) * math.exp(-x / beta)\n", + " | pdf(x) = --------------------------------------\n", + " | math.gamma(alpha) * beta ** alpha\n", + " | \n", + " | gauss(self, mu, sigma)\n", + " | Gaussian distribution.\n", + " | \n", + " | mu is the mean, and sigma is the standard deviation. This is\n", + " | slightly faster than the normalvariate() function.\n", + " | \n", + " | Not thread-safe without a lock around calls.\n", + " | \n", + " | lognormvariate(self, mu, sigma)\n", + " | Log normal distribution.\n", + " | \n", + " | If you take the natural logarithm of this distribution, you'll get a\n", + " | normal distribution with mean mu and standard deviation sigma.\n", + " | mu can have any value, and sigma must be greater than zero.\n", + " | \n", + " | normalvariate(self, mu, sigma)\n", + " | Normal distribution.\n", + " | \n", + " | mu is the mean, and sigma is the standard deviation.\n", + " | \n", + " | paretovariate(self, alpha)\n", + " | Pareto distribution. alpha is the shape parameter.\n", + " | \n", + " | randint(self, a, b)\n", + " | Return random integer in range [a, b], including both end points.\n", + " | \n", + " | randrange(self, start, stop=None, step=1, _int=<class 'int'>)\n", + " | Choose a random item from range(start, stop[, step]).\n", + " | \n", + " | This fixes the problem with randint() which includes the\n", + " | endpoint; in Python this is usually not what you want.\n", + " | \n", + " | sample(self, population, k)\n", + " | Chooses k unique random elements from a population sequence or set.\n", + " | \n", + " | Returns a new list containing elements from the population while\n", + " | leaving the original population unchanged. The resulting list is\n", + " | in selection order so that all sub-slices will also be valid random\n", + " | samples. This allows raffle winners (the sample) to be partitioned\n", + " | into grand prize and second place winners (the subslices).\n", + " | \n", + " | Members of the population need not be hashable or unique. If the\n", + " | population contains repeats, then each occurrence is a possible\n", + " | selection in the sample.\n", + " | \n", + " | To choose a sample in a range of integers, use range as an argument.\n", + " | This is especially fast and space efficient for sampling from a\n", + " | large population: sample(range(10000000), 60)\n", + " | \n", + " | shuffle(self, x, random=None)\n", + " | Shuffle list x in place, and return None.\n", + " | \n", + " | Optional argument random is a 0-argument function returning a\n", + " | random float in [0.0, 1.0); if it is the default None, the\n", + " | standard random.random will be used.\n", + " | \n", + " | triangular(self, low=0.0, high=1.0, mode=None)\n", + " | Triangular distribution.\n", + " | \n", + " | Continuous distribution bounded by given lower and upper limits,\n", + " | and having a given mode value in-between.\n", + " | \n", + " | http://en.wikipedia.org/wiki/Triangular_distribution\n", + " | \n", + " | uniform(self, a, b)\n", + " | Get a random number in the range [a, b) or [a, b] depending on rounding.\n", + " | \n", + " | vonmisesvariate(self, mu, kappa)\n", + " | Circular data distribution.\n", + " | \n", + " | mu is the mean angle, expressed in radians between 0 and 2*pi, and\n", + " | kappa is the concentration parameter, which must be greater than or\n", + " | equal to zero. If kappa is equal to zero, this distribution reduces\n", + " | to a uniform random angle over the range 0 to 2*pi.\n", + " | \n", + " | weibullvariate(self, alpha, beta)\n", + " | Weibull distribution.\n", + " | \n", + " | alpha is the scale parameter and beta is the shape parameter.\n", + " | \n", + " | ----------------------------------------------------------------------\n", + " | Data descriptors inherited from Random:\n", + " | \n", + " | __dict__\n", + " | dictionary for instance variables (if defined)\n", + " | \n", + " | __weakref__\n", + " | list of weak references to the object (if defined)\n", + " | \n", + " | ----------------------------------------------------------------------\n", + " | Data and other attributes inherited from Random:\n", + " | \n", + " | VERSION = 3\n", + " | \n", + " | ----------------------------------------------------------------------\n", + " | Methods inherited from _random.Random:\n", + " | \n", + " | __getattribute__(self, name, /)\n", + " | Return getattr(self, name).\n", + " | \n", + " | ----------------------------------------------------------------------\n", + " | Static methods inherited from _random.Random:\n", + " | \n", + " | __new__(*args, **kwargs) from builtins.type\n", + " | Create and return a new object. See help(type) for accurate signature.\n", + "\n", + "FUNCTIONS\n", + " betavariate(alpha, beta) method of Random instance\n", + " Beta distribution.\n", + " \n", + " Conditions on the parameters are alpha > 0 and beta > 0.\n", + " Returned values range between 0 and 1.\n", + " \n", + " choice(seq) method of Random instance\n", + " Choose a random element from a non-empty sequence.\n", + " \n", + " choices(population, weights=None, *, cum_weights=None, k=1) method of Random instance\n", + " Return a k sized list of population elements chosen with replacement.\n", + " \n", + " If the relative weights or cumulative weights are not specified,\n", + " the selections are made with equal probability.\n", + " \n", + " expovariate(lambd) method of Random instance\n", + " Exponential distribution.\n", + " \n", + " lambd is 1.0 divided by the desired mean. It should be\n", + " nonzero. (The parameter would be called \"lambda\", but that is\n", + " a reserved word in Python.) Returned values range from 0 to\n", + " positive infinity if lambd is positive, and from negative\n", + " infinity to 0 if lambd is negative.\n", + " \n", + " gammavariate(alpha, beta) method of Random instance\n", + " Gamma distribution. Not the gamma function!\n", + " \n", + " Conditions on the parameters are alpha > 0 and beta > 0.\n", + " \n", + " The probability distribution function is:\n", + " \n", + " x ** (alpha - 1) * math.exp(-x / beta)\n", + " pdf(x) = --------------------------------------\n", + " math.gamma(alpha) * beta ** alpha\n", + " \n", + " gauss(mu, sigma) method of Random instance\n", + " Gaussian distribution.\n", + " \n", + " mu is the mean, and sigma is the standard deviation. This is\n", + " slightly faster than the normalvariate() function.\n", + " \n", + " Not thread-safe without a lock around calls.\n", + " \n", + " getrandbits(...) method of Random instance\n", + " getrandbits(k) -> x. Generates an int with k random bits.\n", + " \n", + " getstate() method of Random instance\n", + " Return internal state; can be passed to setstate() later.\n", + " \n", + " lognormvariate(mu, sigma) method of Random instance\n", + " Log normal distribution.\n", + " \n", + " If you take the natural logarithm of this distribution, you'll get a\n", + " normal distribution with mean mu and standard deviation sigma.\n", + " mu can have any value, and sigma must be greater than zero.\n", + " \n", + " normalvariate(mu, sigma) method of Random instance\n", + " Normal distribution.\n", + " \n", + " mu is the mean, and sigma is the standard deviation.\n", + " \n", + " paretovariate(alpha) method of Random instance\n", + " Pareto distribution. alpha is the shape parameter.\n", + " \n", + " randint(a, b) method of Random instance\n", + " Return random integer in range [a, b], including both end points.\n", + " \n", + " random(...) method of Random instance\n", + " random() -> x in the interval [0, 1).\n", + " \n", + " randrange(start, stop=None, step=1, _int=<class 'int'>) method of Random instance\n", + " Choose a random item from range(start, stop[, step]).\n", + " \n", + " This fixes the problem with randint() which includes the\n", + " endpoint; in Python this is usually not what you want.\n", + " \n", + " sample(population, k) method of Random instance\n", + " Chooses k unique random elements from a population sequence or set.\n", + " \n", + " Returns a new list containing elements from the population while\n", + " leaving the original population unchanged. The resulting list is\n", + " in selection order so that all sub-slices will also be valid random\n", + " samples. This allows raffle winners (the sample) to be partitioned\n", + " into grand prize and second place winners (the subslices).\n", + " \n", + " Members of the population need not be hashable or unique. If the\n", + " population contains repeats, then each occurrence is a possible\n", + " selection in the sample.\n", + " \n", + " To choose a sample in a range of integers, use range as an argument.\n", + " This is especially fast and space efficient for sampling from a\n", + " large population: sample(range(10000000), 60)\n", + " \n", + " seed(a=None, version=2) method of Random instance\n", + " Initialize internal state from hashable object.\n", + " \n", + " None or no argument seeds from current time or from an operating\n", + " system specific randomness source if available.\n", + " \n", + " If *a* is an int, all bits are used.\n", + " \n", + " For version 2 (the default), all of the bits are used if *a* is a str,\n", + " bytes, or bytearray. For version 1 (provided for reproducing random\n", + " sequences from older versions of Python), the algorithm for str and\n", + " bytes generates a narrower range of seeds.\n", + " \n", + " setstate(state) method of Random instance\n", + " Restore internal state from object returned by getstate().\n", + " \n", + " shuffle(x, random=None) method of Random instance\n", + " Shuffle list x in place, and return None.\n", + " \n", + " Optional argument random is a 0-argument function returning a\n", + " random float in [0.0, 1.0); if it is the default None, the\n", + " standard random.random will be used.\n", + " \n", + " triangular(low=0.0, high=1.0, mode=None) method of Random instance\n", + " Triangular distribution.\n", + " \n", + " Continuous distribution bounded by given lower and upper limits,\n", + " and having a given mode value in-between.\n", + " \n", + " http://en.wikipedia.org/wiki/Triangular_distribution\n", + " \n", + " uniform(a, b) method of Random instance\n", + " Get a random number in the range [a, b) or [a, b] depending on rounding.\n", + " \n", + " vonmisesvariate(mu, kappa) method of Random instance\n", + " Circular data distribution.\n", + " \n", + " mu is the mean angle, expressed in radians between 0 and 2*pi, and\n", + " kappa is the concentration parameter, which must be greater than or\n", + " equal to zero. If kappa is equal to zero, this distribution reduces\n", + " to a uniform random angle over the range 0 to 2*pi.\n", + " \n", + " weibullvariate(alpha, beta) method of Random instance\n", + " Weibull distribution.\n", + " \n", + " alpha is the scale parameter and beta is the shape parameter.\n", + "\n", + "DATA\n", + " __all__ = ['Random', 'seed', 'random', 'uniform', 'randint', 'choice',...\n", + "\n", + "FILE\n", + " /home/grisalesj/.conda/envs/clase13datos/lib/python3.7/random.py\n", + "\n", + "\n" + ] + } + ], + "source": [ + "help(random)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "2. El experimento consiste en alatoreamente sacar una moneda de la bolsa, lanzarla, y luego sacar las dos monedas que quedan en la bolsa, lanzarlas y anotar los resultado\n", + " Repites esta acción hasta haber lanzado monedas unas 21 veces. Preguntas:\n", + "\n", + " - ¿En qué sentido este ejemplo es distinto a 1?\n", + " - Simular 100 experimentos para estimar cuantas caras esperas obtener en un experimento. \n", + " - Estimar qué desviación esperas entre experimento y experimento. " + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "clase13datos", + "language": "python", + "name": "clase13datos" + }, + "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.7.10" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} diff --git a/Practica1_Probabilidad.ipynb b/Practica1_Probabilidad.ipynb index 46aa9302634b5d80891801bd8b9f93bdd1a81f24..5cfd44960a32015521219af48be3834cf92d66a7 100644 --- a/Practica1_Probabilidad.ipynb +++ b/Practica1_Probabilidad.ipynb @@ -2,7 +2,6 @@ "cells": [ { "cell_type": "markdown", - "id": "preliminary-split", "metadata": {}, "source": [ "# Introducción a la probabilidad\n", @@ -14,7 +13,6 @@ }, { "cell_type": "markdown", - "id": "hindu-introduction", "metadata": {}, "source": [ "## Probabilidad usando monedas\n", @@ -40,7 +38,6 @@ { "cell_type": "code", "execution_count": 1, - "id": "administrative-black", "metadata": {}, "outputs": [], "source": [ @@ -56,7 +53,6 @@ }, { "cell_type": "markdown", - "id": "acknowledged-toddler", "metadata": {}, "source": [ "La función `lanzar_moneda` es la que representa una simulación de 'n' lanzamientos de moneda.\n", @@ -67,7 +63,6 @@ { "cell_type": "code", "execution_count": 2, - "id": "inappropriate-cleanup", "metadata": {}, "outputs": [ { @@ -96,7 +91,6 @@ }, { "cell_type": "markdown", - "id": "directed-longitude", "metadata": {}, "source": [ "A continuación, la funcion `experimentos` repite estos ensayos de lanzar la moneda unas 100 veces el número de veces que queramos, devolviendo el número medio de cabezas en cada ensayo. " @@ -105,7 +99,6 @@ { "cell_type": "code", "execution_count": 3, - "id": "metric-lemon", "metadata": {}, "outputs": [], "source": [ @@ -118,7 +111,6 @@ }, { "cell_type": "markdown", - "id": "motivated-insight", "metadata": {}, "source": [ "Las simulaciones de lanzamiento de monedas nos dan algunos resultados interesantes.\n", @@ -129,7 +121,6 @@ { "cell_type": "code", "execution_count": 4, - "id": "resident-small", "metadata": {}, "outputs": [ { @@ -188,7 +179,6 @@ }, { "cell_type": "markdown", - "id": "organic-aside", "metadata": {}, "source": [ "En 10 ensayos, hay un ligero error, pero este error desaparece casi por completo con 1.000.000 experimentos. \n", @@ -198,7 +188,6 @@ }, { "cell_type": "markdown", - "id": "bound-citizenship", "metadata": {}, "source": [ "## Preguntas\n", @@ -212,7 +201,6 @@ }, { "cell_type": "markdown", - "id": "norwegian-channels", "metadata": {}, "source": [ "## Ensayos de Bernulli\n", @@ -227,7 +215,6 @@ { "cell_type": "code", "execution_count": 5, - "id": "interior-alarm", "metadata": {}, "outputs": [ { @@ -248,7 +235,6 @@ }, { "cell_type": "markdown", - "id": "square-entry", "metadata": {}, "source": [ "## Ejercicios" @@ -256,7 +242,6 @@ }, { "cell_type": "markdown", - "id": "addressed-compiler", "metadata": {}, "source": [ "Los siguientes ejercicios deben ser realizados durante la sesión practica. Lo ideal seria hacer el calculo de la probabilidad, simular los experimentos y comparar los resultados. Para las simulaciones podemos usar las funciones definidas antes e implementar algunas modificaciones.\n", @@ -268,7 +253,6 @@ }, { "cell_type": "markdown", - "id": "familiar-ancient", "metadata": {}, "source": [ "1. El experimento consiste en alatoreamente sacar una moneda de la bolsa, lanzarla, anotar el resultado y volver a introducir la moneda en la bolsa. Repites esta acción hasta haber lanzado monedas unas 21 veces. Preguntas:\n", @@ -280,7 +264,6 @@ }, { "cell_type": "markdown", - "id": "concerned-lending", "metadata": {}, "source": [ "2. El experimento consiste en alatoreamente sacar una moneda de la bolsa, lanzarla, y luego sacar las dos monedas que quedan en la bolsa, lanzarlas y anotar los resultado\n", @@ -293,7 +276,6 @@ }, { "cell_type": "markdown", - "id": "acoustic-society", "metadata": {}, "source": [ "3. Sacamos la primera moneda. \n", diff --git a/solutions.ipynb b/solutions.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..384461da436c6a5e61f6ffa34463caf2052383d9 --- /dev/null +++ b/solutions.ipynb @@ -0,0 +1,1075 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Ejercicios\n", + "\n", + "*Tenemos 3 monedas en una bolsa, una moneda está trucada (99% de probabilidad de salir sello al lanzarse), las otras dos son monedas normales.*\n", + "\n", + "1. El experimento consiste en alatoreamente sacar una moneda de la bolsa, lanzarla, anotar el resultado y volver a introducir la moneda en la bolsa. Repites esta acción hasta haber lanzado monedas unas 21 veces. Preguntas:\n", + "\n", + " - Estimar cuantas caras esperas obtener al terminar el experimento. \n", + " - Simular 100 experimentos para estimar cuantas caras esperas obtener en un experimento. \n", + " - Estimar qué desviación esperas entre experimento y experimento. " + ] + }, + { + "cell_type": "code", + "execution_count": 32, + "metadata": {}, + "outputs": [], + "source": [ + "import random\n" + ] + }, + { + "cell_type": "code", + "execution_count": 147, + "metadata": {}, + "outputs": [], + "source": [ + "Sello = \"Sello\"\n", + "Cara = \"Cara\"\n", + "def flipCoin1():\n", + " choice = random.choice([True,False])\n", + " if choice == True:\n", + " choice = Cara\n", + " else:\n", + " choice = Sello\n", + " return choice\n", + "\n", + "\n", + "def flipCoin2():\n", + " choice = random.choice([True,False,True,True,True,True,True,True,True,True])\n", + " if choice == True:\n", + " choice = Sello\n", + " else:\n", + " choice = Cara\n", + " return choice" + ] + }, + { + "cell_type": "code", + "execution_count": 68, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'Sello'" + ] + }, + "execution_count": 68, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "flipCoin2()" + ] + }, + { + "cell_type": "code", + "execution_count": 148, + "metadata": {}, + "outputs": [], + "source": [ + "moneda = []\n", + "def sacamonedas(n):\n", + " sellos = 0\n", + " p = 0\n", + " q = 0\n", + " for i in range(0,n,1):\n", + " value = random.randint(0, 3)\n", + " if value == 0:\n", + " tmp = flipCoin2()\n", + " moneda.append(tmp)\n", + " if tmp == \"Sello\":\n", + " sellos +=1\n", + " else:\n", + " tmp = flipCoin1()\n", + " moneda.append(tmp) \n", + " if tmp == \"Sello\":\n", + " sellos +=1\n", + " p = sellos/n\n", + " q = 1-p\n", + " return moneda, sellos, p, q" + ] + }, + { + "cell_type": "code", + "execution_count": 149, + "metadata": { + "collapsed": true + }, + "outputs": [ + { + "data": { + "text/plain": [ + "(['Cara',\n", + " 'Sello',\n", + " 'Cara',\n", + " 'Sello',\n", + " 'Sello',\n", + " 'Sello',\n", + " 'Cara',\n", + " 'Cara',\n", + " 'Sello',\n", + " 'Cara',\n", + " 'Sello',\n", + " 'Sello',\n", + " 'Sello',\n", + " 'Sello',\n", + " 'Sello',\n", + " 'Sello',\n", + " 'Cara',\n", + " 'Sello',\n", + " 'Cara',\n", + " 'Sello',\n", + " 'Sello',\n", + " 'Sello',\n", + " 'Sello',\n", + " 'Sello',\n", + " 'Cara',\n", + " 'Cara',\n", + " 'Sello',\n", + " 'Sello',\n", + " 'Cara',\n", + " 'Sello',\n", + " 'Sello',\n", + " 'Cara',\n", + " 'Sello',\n", + " 'Sello',\n", + " 'Sello',\n", + " 'Cara',\n", + " 'Sello',\n", + " 'Cara',\n", + " 'Sello',\n", + " 'Cara',\n", + " 'Sello',\n", + " 'Sello',\n", + " 'Cara',\n", + " 'Sello',\n", + " 'Cara',\n", + " 'Sello',\n", + " 'Cara',\n", + " 'Cara',\n", + " 'Cara',\n", + " 'Cara',\n", + " 'Cara',\n", + " 'Cara',\n", + " 'Sello',\n", + " 'Cara',\n", + " 'Sello',\n", + " 'Sello',\n", + " 'Sello',\n", + " 'Sello',\n", + " 'Cara',\n", + " 'Sello',\n", + " 'Cara',\n", + " 'Cara',\n", + " 'Cara',\n", + " 'Sello',\n", + " 'Sello',\n", + " 'Sello',\n", + " 'Sello',\n", + " 'Sello',\n", + " 'Cara',\n", + " 'Sello',\n", + " 'Sello',\n", + " 'Cara',\n", + " 'Cara',\n", + " 'Sello',\n", + " 'Sello',\n", + " 'Sello',\n", + " 'Sello',\n", + " 'Cara',\n", + " 'Cara',\n", + " 'Cara',\n", + " 'Cara',\n", + " 'Sello',\n", + " 'Cara',\n", + " 'Sello',\n", + " 'Sello',\n", + " 'Sello',\n", + " 'Sello',\n", + " 'Sello',\n", + " 'Sello',\n", + " 'Cara',\n", + " 'Sello',\n", + " 'Sello',\n", + " 'Sello',\n", + " 'Sello',\n", + " 'Sello',\n", + " 'Sello',\n", + " 'Cara',\n", + " 'Cara',\n", + " 'Sello',\n", + " 'Sello'],\n", + " 62,\n", + " 0.62,\n", + " 0.38)" + ] + }, + "execution_count": 149, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "sacamonedas(100)" + ] + }, + { + "cell_type": "code", + "execution_count": 132, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "(array([61., 0., 0., 0., 0., 0., 0., 0., 0., 39.]),\n", + " array([0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1. ]),\n", + " <BarContainer object of 10 artists>)" + ] + }, + "execution_count": 132, + "metadata": {}, + "output_type": "execute_result" + }, + { + "data": { + "image/png": "iVBORw0KGgoAAAANSUhEUgAAAXAAAAD4CAYAAAD1jb0+AAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjMuNCwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy8QVMy6AAAACXBIWXMAAAsTAAALEwEAmpwYAAAM/klEQVR4nO3df6zd9V3H8efLXhCzuXXY67UC2SVZZWHL+HXBkSkTcAuOxXYJaUYW02iT/jPNjC6uc/+4ZBr4Q8dc3EwDyDVBAVHWZphtpNIZjbLdjp+lY3SkDcWWXrToWCJb4e0f51u9uT235/Tee+7Nxz0fCTnn++t835c/nv3223POTVUhSWrPj632AJKkxTHgktQoAy5JjTLgktQoAy5JjRpbyZOtW7euJicnV/KUktS8vXv3vlRV4/PXr2jAJycnmZmZWclTSlLzkhzqt95bKJLUKAMuSY0y4JLUKAMuSY0y4JLUKAMuSY0y4JLUKAMuSY0y4JLUqKE+iZlkLXA78E6ggN8AngHuBSaBg8Dmqjo+iiEBJrc/OKqXPq2Dt9y4KueVpEGGvQL/HPCVqno7cAmwH9gO7K6qDcDublmStEIGBjzJm4FrgDsAquoHVfUysBGY7nabBjaNZkRJUj/DXIFfCMwCf5Hk0SS3J3kDMFFVR7p9jgIT/Q5Osi3JTJKZ2dnZ5ZlakjRUwMeAy4EvVtVlwPeZd7uker8Zue9vR66qHVU1VVVT4+OnfBuiJGmRhgn4YeBwVT3SLd9PL+gvJlkP0D0eG82IkqR+Bga8qo4Czye5qFt1PfA0s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xHeSfCHJe5OcBXweuKmqrgDuBP5woRdI8rPArcB1wKXAlUk2jXxyST/q3gns7bP+v4EPVdXl9CL/x90VN8AG4AtV9Y6qOgR8qvuE5ruA9yZ515kMsKq3UKrqlSRXAL9I7we9F/gMvf8xD3U/8xrgyGle5kpgT1XNAiS5G7gG+NLoJpekBQX4oyTXAK/T+96oiW7boar61zn7bu6+L2qM3h2Ji4Enhj3RqgYcoKpeA/YAe5I8CXwU2FdVV6/qYJJ0evuAm/qs/wgwDlxRVT9MchA4p9v2/ZM7JbkQ+DhwZVUdT3LXnP2Gsqq3UJJclGTDnFWXAvuB8e4fOElyVpJ3nOZlvkHvrx7ruu8ovxn4+qhmlqTOPwA/3l1BA9DdAnkrcKyL97Us8E2CwJvoBf0/k0zQ+90KZ2S1r8DfCHw+yVrgBHCA3lfP7gD+NMmb6c14G70/7U5RVUe63wb0ML2/ujxYVTtHP7qkH2VVVUk+BNyW5BP07n0fBP6AXr+eBGaAby9w/ONJHu22Pw/885nO4EfpJalRq/0uFEnSIhlwSWqUAZekRhlwSWqUAZekRhlwSWqUAZekRv0P+STaYw2wR50AAAAASUVORK5CYII=\n", + "text/plain": [ + "<Figure size 432x288 with 1 Axes>" + ] + }, + "metadata": { + "needs_background": "light" + }, + "output_type": "display_data" + } + ], + "source": [ + "import pandas as pd\n", + "import matplotlib.pyplot as plt\n", + "\n", + "plt.hist(moneda)" + ] + }, + { + "cell_type": "code", + "execution_count": 106, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Al lanzar la moneda 10000 veces, la proporcion de vece que obtuvimos Sello: 0.5978\n", + "Al lanzar la moneda 10000 veces, la proporcion de vece que obtuvimos Cara: 0.4022\n", + "\n" + ] + } + ], + "source": [ + "print ('Al lanzar la moneda 10000 veces, la proporcion de vece que obtuvimos Sello: ',prob)\n", + "q = 1-prob\n", + "print ('Al lanzar la moneda 10000 veces, la proporcion de vece que obtuvimos Cara: ',q)\n", + "print()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Lo que se hace acá es hacer el experimento n veces para tener una estadÃstica...\n", + "\n", + "def experimentos(n,n_lanzamientos):\n", + " experimento = []\n", + " for i in range(n):\n", + " experimento.append(lanzar_moneda(n_lanzamientos))\n", + " return (experimento)" + ] + }, + { + "cell_type": "code", + "execution_count": 107, + "metadata": {}, + "outputs": [ + { + "ename": "TypeError", + "evalue": "'int' object is not iterable", + "output_type": "error", + "traceback": [ + "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", + "\u001b[0;32m<ipython-input-107-1d5e300857b9>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[0;32mfrom\u001b[0m \u001b[0mstatistics\u001b[0m \u001b[0;32mimport\u001b[0m \u001b[0mmean\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mstdev\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 3\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 4\u001b[0;31m \u001b[0mprint\u001b[0m \u001b[0;34m(\u001b[0m\u001b[0;34m'Con 10000 experimentos, valor medio:'\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0mmean\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0msellos\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m'desviación estandar:'\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mstdev\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0msellos\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 5\u001b[0m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", + "\u001b[0;32m~/.conda/envs/clase13datos/lib/python3.7/statistics.py\u001b[0m in \u001b[0;36mmean\u001b[0;34m(data)\u001b[0m\n\u001b[1;32m 304\u001b[0m \u001b[0mIf\u001b[0m\u001b[0;31m \u001b[0m\u001b[0;31m`\u001b[0m\u001b[0;31m`\u001b[0m\u001b[0mdata\u001b[0m\u001b[0;31m`\u001b[0m\u001b[0;31m`\u001b[0m \u001b[0;32mis\u001b[0m \u001b[0mempty\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mStatisticsError\u001b[0m \u001b[0mwill\u001b[0m \u001b[0mbe\u001b[0m \u001b[0mraised\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 305\u001b[0m \"\"\"\n\u001b[0;32m--> 306\u001b[0;31m \u001b[0;32mif\u001b[0m \u001b[0miter\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mdata\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;32mis\u001b[0m \u001b[0mdata\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 307\u001b[0m \u001b[0mdata\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mlist\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mdata\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 308\u001b[0m \u001b[0mn\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mlen\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mdata\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", + "\u001b[0;31mTypeError\u001b[0m: 'int' object is not iterable" + ] + } + ], + "source": [ + "import matplotlib.pyplot as plt\n", + "from statistics import mean, stdev \n", + "\n", + "print ('Con 10000 experimentos, valor medio:',mean(sellos), 'desviación estandar:', stdev(sellos))\n", + "print()" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "code", + "execution_count": 21, + "metadata": {}, + "outputs": [], + "source": [ + "\n", + "moneda = []\n", + "\n", + "choice = random.randint(0, 3)\n", + "\n", + "\n", + "def lanzar_truncada():\n", + " sello = 0\n", + " for i in range(n):\n", + " if random.random() <= 0.9:\n", + " sello +=1 \n", + " return sello/n\n", + "\n", + "def lanzar_moneda(n):\n", + " sello = 0\n", + " for i in range(n):\n", + " if random.random() <= 0.5:\n", + " sello +=1 \n", + " return sello/n" + ] + }, + { + "cell_type": "code", + "execution_count": 31, + "metadata": {}, + "outputs": [], + "source": [ + "monedas= []\n", + "tipo_moneda =0\n", + "def moneda(n):\n", + " for i in range(n):\n", + " tipo_moneda = random.random()\n", + " if tipo_moneda <= 0.33:\n", + " valor = lanzar_truncada(1)\n", + " monedas.append(valor)\n", + " else:\n", + " valor = lanzar_moneda(1)\n", + " monedas.append(valor)\n", + " print(monedas)\n" + ] + }, + { + "cell_type": "code", + "execution_count": 32, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[1.0, 0.0, 1.0, 1.0, 0.0, 1.0]\n" + ] + } + ], + "source": [ + "moneda(6)" + ] + }, + { + "cell_type": "code", + "execution_count": 30, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Help on module random:\n", + "\n", + "NAME\n", + " random - Random variable generators.\n", + "\n", + "MODULE REFERENCE\n", + " https://docs.python.org/3.7/library/random\n", + " \n", + " The following documentation is automatically generated from the Python\n", + " source files. It may be incomplete, incorrect or include features that\n", + " are considered implementation detail and may vary between Python\n", + " implementations. When in doubt, consult the module reference at the\n", + " location listed above.\n", + "\n", + "DESCRIPTION\n", + " integers\n", + " --------\n", + " uniform within range\n", + " \n", + " sequences\n", + " ---------\n", + " pick random element\n", + " pick random sample\n", + " pick weighted random sample\n", + " generate random permutation\n", + " \n", + " distributions on the real line:\n", + " ------------------------------\n", + " uniform\n", + " triangular\n", + " normal (Gaussian)\n", + " lognormal\n", + " negative exponential\n", + " gamma\n", + " beta\n", + " pareto\n", + " Weibull\n", + " \n", + " distributions on the circle (angles 0 to 2pi)\n", + " ---------------------------------------------\n", + " circular uniform\n", + " von Mises\n", + " \n", + " General notes on the underlying Mersenne Twister core generator:\n", + " \n", + " * The period is 2**19937-1.\n", + " * It is one of the most extensively tested generators in existence.\n", + " * The random() method is implemented in C, executes in a single Python step,\n", + " and is, therefore, threadsafe.\n", + "\n", + "CLASSES\n", + " _random.Random(builtins.object)\n", + " Random\n", + " SystemRandom\n", + " \n", + " class Random(_random.Random)\n", + " | Random(x=None)\n", + " | \n", + " | Random number generator base class used by bound module functions.\n", + " | \n", + " | Used to instantiate instances of Random to get generators that don't\n", + " | share state.\n", + " | \n", + " | Class Random can also be subclassed if you want to use a different basic\n", + " | generator of your own devising: in that case, override the following\n", + " | methods: random(), seed(), getstate(), and setstate().\n", + " | Optionally, implement a getrandbits() method so that randrange()\n", + " | can cover arbitrarily large ranges.\n", + " | \n", + " | Method resolution order:\n", + " | Random\n", + " | _random.Random\n", + " | builtins.object\n", + " | \n", + " | Methods defined here:\n", + " | \n", + " | __getstate__(self)\n", + " | # Issue 17489: Since __reduce__ was defined to fix #759889 this is no\n", + " | # longer called; we leave it here because it has been here since random was\n", + " | # rewritten back in 2001 and why risk breaking something.\n", + " | \n", + " | __init__(self, x=None)\n", + " | Initialize an instance.\n", + " | \n", + " | Optional argument x controls seeding, as for Random.seed().\n", + " | \n", + " | __reduce__(self)\n", + " | Helper for pickle.\n", + " | \n", + " | __setstate__(self, state)\n", + " | \n", + " | betavariate(self, alpha, beta)\n", + " | Beta distribution.\n", + " | \n", + " | Conditions on the parameters are alpha > 0 and beta > 0.\n", + " | Returned values range between 0 and 1.\n", + " | \n", + " | choice(self, seq)\n", + " | Choose a random element from a non-empty sequence.\n", + " | \n", + " | choices(self, population, weights=None, *, cum_weights=None, k=1)\n", + " | Return a k sized list of population elements chosen with replacement.\n", + " | \n", + " | If the relative weights or cumulative weights are not specified,\n", + " | the selections are made with equal probability.\n", + " | \n", + " | expovariate(self, lambd)\n", + " | Exponential distribution.\n", + " | \n", + " | lambd is 1.0 divided by the desired mean. It should be\n", + " | nonzero. (The parameter would be called \"lambda\", but that is\n", + " | a reserved word in Python.) Returned values range from 0 to\n", + " | positive infinity if lambd is positive, and from negative\n", + " | infinity to 0 if lambd is negative.\n", + " | \n", + " | gammavariate(self, alpha, beta)\n", + " | Gamma distribution. Not the gamma function!\n", + " | \n", + " | Conditions on the parameters are alpha > 0 and beta > 0.\n", + " | \n", + " | The probability distribution function is:\n", + " | \n", + " | x ** (alpha - 1) * math.exp(-x / beta)\n", + " | pdf(x) = --------------------------------------\n", + " | math.gamma(alpha) * beta ** alpha\n", + " | \n", + " | gauss(self, mu, sigma)\n", + " | Gaussian distribution.\n", + " | \n", + " | mu is the mean, and sigma is the standard deviation. This is\n", + " | slightly faster than the normalvariate() function.\n", + " | \n", + " | Not thread-safe without a lock around calls.\n", + " | \n", + " | getstate(self)\n", + " | Return internal state; can be passed to setstate() later.\n", + " | \n", + " | lognormvariate(self, mu, sigma)\n", + " | Log normal distribution.\n", + " | \n", + " | If you take the natural logarithm of this distribution, you'll get a\n", + " | normal distribution with mean mu and standard deviation sigma.\n", + " | mu can have any value, and sigma must be greater than zero.\n", + " | \n", + " | normalvariate(self, mu, sigma)\n", + " | Normal distribution.\n", + " | \n", + " | mu is the mean, and sigma is the standard deviation.\n", + " | \n", + " | paretovariate(self, alpha)\n", + " | Pareto distribution. alpha is the shape parameter.\n", + " | \n", + " | randint(self, a, b)\n", + " | Return random integer in range [a, b], including both end points.\n", + " | \n", + " | randrange(self, start, stop=None, step=1, _int=<class 'int'>)\n", + " | Choose a random item from range(start, stop[, step]).\n", + " | \n", + " | This fixes the problem with randint() which includes the\n", + " | endpoint; in Python this is usually not what you want.\n", + " | \n", + " | sample(self, population, k)\n", + " | Chooses k unique random elements from a population sequence or set.\n", + " | \n", + " | Returns a new list containing elements from the population while\n", + " | leaving the original population unchanged. The resulting list is\n", + " | in selection order so that all sub-slices will also be valid random\n", + " | samples. This allows raffle winners (the sample) to be partitioned\n", + " | into grand prize and second place winners (the subslices).\n", + " | \n", + " | Members of the population need not be hashable or unique. If the\n", + " | population contains repeats, then each occurrence is a possible\n", + " | selection in the sample.\n", + " | \n", + " | To choose a sample in a range of integers, use range as an argument.\n", + " | This is especially fast and space efficient for sampling from a\n", + " | large population: sample(range(10000000), 60)\n", + " | \n", + " | seed(self, a=None, version=2)\n", + " | Initialize internal state from hashable object.\n", + " | \n", + " | None or no argument seeds from current time or from an operating\n", + " | system specific randomness source if available.\n", + " | \n", + " | If *a* is an int, all bits are used.\n", + " | \n", + " | For version 2 (the default), all of the bits are used if *a* is a str,\n", + " | bytes, or bytearray. For version 1 (provided for reproducing random\n", + " | sequences from older versions of Python), the algorithm for str and\n", + " | bytes generates a narrower range of seeds.\n", + " | \n", + " | setstate(self, state)\n", + " | Restore internal state from object returned by getstate().\n", + " | \n", + " | shuffle(self, x, random=None)\n", + " | Shuffle list x in place, and return None.\n", + " | \n", + " | Optional argument random is a 0-argument function returning a\n", + " | random float in [0.0, 1.0); if it is the default None, the\n", + " | standard random.random will be used.\n", + " | \n", + " | triangular(self, low=0.0, high=1.0, mode=None)\n", + " | Triangular distribution.\n", + " | \n", + " | Continuous distribution bounded by given lower and upper limits,\n", + " | and having a given mode value in-between.\n", + " | \n", + " | http://en.wikipedia.org/wiki/Triangular_distribution\n", + " | \n", + " | uniform(self, a, b)\n", + " | Get a random number in the range [a, b) or [a, b] depending on rounding.\n", + " | \n", + " | vonmisesvariate(self, mu, kappa)\n", + " | Circular data distribution.\n", + " | \n", + " | mu is the mean angle, expressed in radians between 0 and 2*pi, and\n", + " | kappa is the concentration parameter, which must be greater than or\n", + " | equal to zero. If kappa is equal to zero, this distribution reduces\n", + " | to a uniform random angle over the range 0 to 2*pi.\n", + " | \n", + " | weibullvariate(self, alpha, beta)\n", + " | Weibull distribution.\n", + " | \n", + " | alpha is the scale parameter and beta is the shape parameter.\n", + " | \n", + " | ----------------------------------------------------------------------\n", + " | Data descriptors defined here:\n", + " | \n", + " | __dict__\n", + " | dictionary for instance variables (if defined)\n", + " | \n", + " | __weakref__\n", + " | list of weak references to the object (if defined)\n", + " | \n", + " | ----------------------------------------------------------------------\n", + " | Data and other attributes defined here:\n", + " | \n", + " | VERSION = 3\n", + " | \n", + " | ----------------------------------------------------------------------\n", + " | Methods inherited from _random.Random:\n", + " | \n", + " | __getattribute__(self, name, /)\n", + " | Return getattr(self, name).\n", + " | \n", + " | getrandbits(...)\n", + " | getrandbits(k) -> x. Generates an int with k random bits.\n", + " | \n", + " | random(...)\n", + " | random() -> x in the interval [0, 1).\n", + " | \n", + " | ----------------------------------------------------------------------\n", + " | Static methods inherited from _random.Random:\n", + " | \n", + " | __new__(*args, **kwargs) from builtins.type\n", + " | Create and return a new object. See help(type) for accurate signature.\n", + " \n", + " class SystemRandom(Random)\n", + " | SystemRandom(x=None)\n", + " | \n", + " | Alternate random number generator using sources provided\n", + " | by the operating system (such as /dev/urandom on Unix or\n", + " | CryptGenRandom on Windows).\n", + " | \n", + " | Not available on all systems (see os.urandom() for details).\n", + " | \n", + " | Method resolution order:\n", + " | SystemRandom\n", + " | Random\n", + " | _random.Random\n", + " | builtins.object\n", + " | \n", + " | Methods defined here:\n", + " | \n", + " | getrandbits(self, k)\n", + " | getrandbits(k) -> x. Generates an int with k random bits.\n", + " | \n", + " | getstate = _notimplemented(self, *args, **kwds)\n", + " | \n", + " | random(self)\n", + " | Get the next random number in the range [0.0, 1.0).\n", + " | \n", + " | seed(self, *args, **kwds)\n", + " | Stub method. Not used for a system random number generator.\n", + " | \n", + " | setstate = _notimplemented(self, *args, **kwds)\n", + " | \n", + " | ----------------------------------------------------------------------\n", + " | Methods inherited from Random:\n", + " | \n", + " | __getstate__(self)\n", + " | # Issue 17489: Since __reduce__ was defined to fix #759889 this is no\n", + " | # longer called; we leave it here because it has been here since random was\n", + " | # rewritten back in 2001 and why risk breaking something.\n", + " | \n", + " | __init__(self, x=None)\n", + " | Initialize an instance.\n", + " | \n", + " | Optional argument x controls seeding, as for Random.seed().\n", + " | \n", + " | __reduce__(self)\n", + " | Helper for pickle.\n", + " | \n", + " | __setstate__(self, state)\n", + " | \n", + " | betavariate(self, alpha, beta)\n", + " | Beta distribution.\n", + " | \n", + " | Conditions on the parameters are alpha > 0 and beta > 0.\n", + " | Returned values range between 0 and 1.\n", + " | \n", + " | choice(self, seq)\n", + " | Choose a random element from a non-empty sequence.\n", + " | \n", + " | choices(self, population, weights=None, *, cum_weights=None, k=1)\n", + " | Return a k sized list of population elements chosen with replacement.\n", + " | \n", + " | If the relative weights or cumulative weights are not specified,\n", + " | the selections are made with equal probability.\n", + " | \n", + " | expovariate(self, lambd)\n", + " | Exponential distribution.\n", + " | \n", + " | lambd is 1.0 divided by the desired mean. It should be\n", + " | nonzero. (The parameter would be called \"lambda\", but that is\n", + " | a reserved word in Python.) Returned values range from 0 to\n", + " | positive infinity if lambd is positive, and from negative\n", + " | infinity to 0 if lambd is negative.\n", + " | \n", + " | gammavariate(self, alpha, beta)\n", + " | Gamma distribution. Not the gamma function!\n", + " | \n", + " | Conditions on the parameters are alpha > 0 and beta > 0.\n", + " | \n", + " | The probability distribution function is:\n", + " | \n", + " | x ** (alpha - 1) * math.exp(-x / beta)\n", + " | pdf(x) = --------------------------------------\n", + " | math.gamma(alpha) * beta ** alpha\n", + " | \n", + " | gauss(self, mu, sigma)\n", + " | Gaussian distribution.\n", + " | \n", + " | mu is the mean, and sigma is the standard deviation. This is\n", + " | slightly faster than the normalvariate() function.\n", + " | \n", + " | Not thread-safe without a lock around calls.\n", + " | \n", + " | lognormvariate(self, mu, sigma)\n", + " | Log normal distribution.\n", + " | \n", + " | If you take the natural logarithm of this distribution, you'll get a\n", + " | normal distribution with mean mu and standard deviation sigma.\n", + " | mu can have any value, and sigma must be greater than zero.\n", + " | \n", + " | normalvariate(self, mu, sigma)\n", + " | Normal distribution.\n", + " | \n", + " | mu is the mean, and sigma is the standard deviation.\n", + " | \n", + " | paretovariate(self, alpha)\n", + " | Pareto distribution. alpha is the shape parameter.\n", + " | \n", + " | randint(self, a, b)\n", + " | Return random integer in range [a, b], including both end points.\n", + " | \n", + " | randrange(self, start, stop=None, step=1, _int=<class 'int'>)\n", + " | Choose a random item from range(start, stop[, step]).\n", + " | \n", + " | This fixes the problem with randint() which includes the\n", + " | endpoint; in Python this is usually not what you want.\n", + " | \n", + " | sample(self, population, k)\n", + " | Chooses k unique random elements from a population sequence or set.\n", + " | \n", + " | Returns a new list containing elements from the population while\n", + " | leaving the original population unchanged. The resulting list is\n", + " | in selection order so that all sub-slices will also be valid random\n", + " | samples. This allows raffle winners (the sample) to be partitioned\n", + " | into grand prize and second place winners (the subslices).\n", + " | \n", + " | Members of the population need not be hashable or unique. If the\n", + " | population contains repeats, then each occurrence is a possible\n", + " | selection in the sample.\n", + " | \n", + " | To choose a sample in a range of integers, use range as an argument.\n", + " | This is especially fast and space efficient for sampling from a\n", + " | large population: sample(range(10000000), 60)\n", + " | \n", + " | shuffle(self, x, random=None)\n", + " | Shuffle list x in place, and return None.\n", + " | \n", + " | Optional argument random is a 0-argument function returning a\n", + " | random float in [0.0, 1.0); if it is the default None, the\n", + " | standard random.random will be used.\n", + " | \n", + " | triangular(self, low=0.0, high=1.0, mode=None)\n", + " | Triangular distribution.\n", + " | \n", + " | Continuous distribution bounded by given lower and upper limits,\n", + " | and having a given mode value in-between.\n", + " | \n", + " | http://en.wikipedia.org/wiki/Triangular_distribution\n", + " | \n", + " | uniform(self, a, b)\n", + " | Get a random number in the range [a, b) or [a, b] depending on rounding.\n", + " | \n", + " | vonmisesvariate(self, mu, kappa)\n", + " | Circular data distribution.\n", + " | \n", + " | mu is the mean angle, expressed in radians between 0 and 2*pi, and\n", + " | kappa is the concentration parameter, which must be greater than or\n", + " | equal to zero. If kappa is equal to zero, this distribution reduces\n", + " | to a uniform random angle over the range 0 to 2*pi.\n", + " | \n", + " | weibullvariate(self, alpha, beta)\n", + " | Weibull distribution.\n", + " | \n", + " | alpha is the scale parameter and beta is the shape parameter.\n", + " | \n", + " | ----------------------------------------------------------------------\n", + " | Data descriptors inherited from Random:\n", + " | \n", + " | __dict__\n", + " | dictionary for instance variables (if defined)\n", + " | \n", + " | __weakref__\n", + " | list of weak references to the object (if defined)\n", + " | \n", + " | ----------------------------------------------------------------------\n", + " | Data and other attributes inherited from Random:\n", + " | \n", + " | VERSION = 3\n", + " | \n", + " | ----------------------------------------------------------------------\n", + " | Methods inherited from _random.Random:\n", + " | \n", + " | __getattribute__(self, name, /)\n", + " | Return getattr(self, name).\n", + " | \n", + " | ----------------------------------------------------------------------\n", + " | Static methods inherited from _random.Random:\n", + " | \n", + " | __new__(*args, **kwargs) from builtins.type\n", + " | Create and return a new object. See help(type) for accurate signature.\n", + "\n", + "FUNCTIONS\n", + " betavariate(alpha, beta) method of Random instance\n", + " Beta distribution.\n", + " \n", + " Conditions on the parameters are alpha > 0 and beta > 0.\n", + " Returned values range between 0 and 1.\n", + " \n", + " choice(seq) method of Random instance\n", + " Choose a random element from a non-empty sequence.\n", + " \n", + " choices(population, weights=None, *, cum_weights=None, k=1) method of Random instance\n", + " Return a k sized list of population elements chosen with replacement.\n", + " \n", + " If the relative weights or cumulative weights are not specified,\n", + " the selections are made with equal probability.\n", + " \n", + " expovariate(lambd) method of Random instance\n", + " Exponential distribution.\n", + " \n", + " lambd is 1.0 divided by the desired mean. It should be\n", + " nonzero. (The parameter would be called \"lambda\", but that is\n", + " a reserved word in Python.) Returned values range from 0 to\n", + " positive infinity if lambd is positive, and from negative\n", + " infinity to 0 if lambd is negative.\n", + " \n", + " gammavariate(alpha, beta) method of Random instance\n", + " Gamma distribution. Not the gamma function!\n", + " \n", + " Conditions on the parameters are alpha > 0 and beta > 0.\n", + " \n", + " The probability distribution function is:\n", + " \n", + " x ** (alpha - 1) * math.exp(-x / beta)\n", + " pdf(x) = --------------------------------------\n", + " math.gamma(alpha) * beta ** alpha\n", + " \n", + " gauss(mu, sigma) method of Random instance\n", + " Gaussian distribution.\n", + " \n", + " mu is the mean, and sigma is the standard deviation. This is\n", + " slightly faster than the normalvariate() function.\n", + " \n", + " Not thread-safe without a lock around calls.\n", + " \n", + " getrandbits(...) method of Random instance\n", + " getrandbits(k) -> x. Generates an int with k random bits.\n", + " \n", + " getstate() method of Random instance\n", + " Return internal state; can be passed to setstate() later.\n", + " \n", + " lognormvariate(mu, sigma) method of Random instance\n", + " Log normal distribution.\n", + " \n", + " If you take the natural logarithm of this distribution, you'll get a\n", + " normal distribution with mean mu and standard deviation sigma.\n", + " mu can have any value, and sigma must be greater than zero.\n", + " \n", + " normalvariate(mu, sigma) method of Random instance\n", + " Normal distribution.\n", + " \n", + " mu is the mean, and sigma is the standard deviation.\n", + " \n", + " paretovariate(alpha) method of Random instance\n", + " Pareto distribution. alpha is the shape parameter.\n", + " \n", + " randint(a, b) method of Random instance\n", + " Return random integer in range [a, b], including both end points.\n", + " \n", + " random(...) method of Random instance\n", + " random() -> x in the interval [0, 1).\n", + " \n", + " randrange(start, stop=None, step=1, _int=<class 'int'>) method of Random instance\n", + " Choose a random item from range(start, stop[, step]).\n", + " \n", + " This fixes the problem with randint() which includes the\n", + " endpoint; in Python this is usually not what you want.\n", + " \n", + " sample(population, k) method of Random instance\n", + " Chooses k unique random elements from a population sequence or set.\n", + " \n", + " Returns a new list containing elements from the population while\n", + " leaving the original population unchanged. The resulting list is\n", + " in selection order so that all sub-slices will also be valid random\n", + " samples. This allows raffle winners (the sample) to be partitioned\n", + " into grand prize and second place winners (the subslices).\n", + " \n", + " Members of the population need not be hashable or unique. If the\n", + " population contains repeats, then each occurrence is a possible\n", + " selection in the sample.\n", + " \n", + " To choose a sample in a range of integers, use range as an argument.\n", + " This is especially fast and space efficient for sampling from a\n", + " large population: sample(range(10000000), 60)\n", + " \n", + " seed(a=None, version=2) method of Random instance\n", + " Initialize internal state from hashable object.\n", + " \n", + " None or no argument seeds from current time or from an operating\n", + " system specific randomness source if available.\n", + " \n", + " If *a* is an int, all bits are used.\n", + " \n", + " For version 2 (the default), all of the bits are used if *a* is a str,\n", + " bytes, or bytearray. For version 1 (provided for reproducing random\n", + " sequences from older versions of Python), the algorithm for str and\n", + " bytes generates a narrower range of seeds.\n", + " \n", + " setstate(state) method of Random instance\n", + " Restore internal state from object returned by getstate().\n", + " \n", + " shuffle(x, random=None) method of Random instance\n", + " Shuffle list x in place, and return None.\n", + " \n", + " Optional argument random is a 0-argument function returning a\n", + " random float in [0.0, 1.0); if it is the default None, the\n", + " standard random.random will be used.\n", + " \n", + " triangular(low=0.0, high=1.0, mode=None) method of Random instance\n", + " Triangular distribution.\n", + " \n", + " Continuous distribution bounded by given lower and upper limits,\n", + " and having a given mode value in-between.\n", + " \n", + " http://en.wikipedia.org/wiki/Triangular_distribution\n", + " \n", + " uniform(a, b) method of Random instance\n", + " Get a random number in the range [a, b) or [a, b] depending on rounding.\n", + " \n", + " vonmisesvariate(mu, kappa) method of Random instance\n", + " Circular data distribution.\n", + " \n", + " mu is the mean angle, expressed in radians between 0 and 2*pi, and\n", + " kappa is the concentration parameter, which must be greater than or\n", + " equal to zero. If kappa is equal to zero, this distribution reduces\n", + " to a uniform random angle over the range 0 to 2*pi.\n", + " \n", + " weibullvariate(alpha, beta) method of Random instance\n", + " Weibull distribution.\n", + " \n", + " alpha is the scale parameter and beta is the shape parameter.\n", + "\n", + "DATA\n", + " __all__ = ['Random', 'seed', 'random', 'uniform', 'randint', 'choice',...\n", + "\n", + "FILE\n", + " /home/grisalesj/.conda/envs/clase13datos/lib/python3.7/random.py\n", + "\n", + "\n" + ] + } + ], + "source": [ + "help(random)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "2. El experimento consiste en alatoreamente sacar una moneda de la bolsa, lanzarla, y luego sacar las dos monedas que quedan en la bolsa, lanzarlas y anotar los resultado\n", + " Repites esta acción hasta haber lanzado monedas unas 21 veces. Preguntas:\n", + "\n", + " - ¿En qué sentido este ejemplo es distinto a 1?\n", + " - Simular 100 experimentos para estimar cuantas caras esperas obtener en un experimento. \n", + " - Estimar qué desviación esperas entre experimento y experimento. " + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "clase13datos", + "language": "python", + "name": "clase13datos" + }, + "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.7.10" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +}