From 45e38d949420b32ca53e9fe4c0b452b7c780bcc0 Mon Sep 17 00:00:00 2001 From: ngumalbright Date: Sun, 18 Feb 2024 20:38:10 +0000 Subject: [PATCH] Adding lab3 exercise 2 to my repository --- Lab03/Lab03-2.ipynb | 105 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 105 insertions(+) create mode 100644 Lab03/Lab03-2.ipynb diff --git a/Lab03/Lab03-2.ipynb b/Lab03/Lab03-2.ipynb new file mode 100644 index 0000000..19c2575 --- /dev/null +++ b/Lab03/Lab03-2.ipynb @@ -0,0 +1,105 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 1, + "id": "0986bdf6", + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "For convergence criterion 0.01:\n", + "Average number of draws: 37.2\n", + "Standard deviation of draws: 75.69500203668227\n", + "\n", + "For convergence criterion 0.001:\n", + "Average number of draws: 839.4\n", + "Standard deviation of draws: 1430.1452296105379\n", + "\n", + "For convergence criterion 0.0001:\n", + "Average number of draws: 286679.5\n", + "Standard deviation of draws: 751160.3040932001\n", + "\n", + "For convergence criterion 1e-05:\n", + "Average number of draws: 1135232\n", + "Standard deviation of draws: 3526521.0381986317\n", + "\n" + ] + } + ], + "source": [ + "import random\n", + "import statistics\n", + "\n", + "def estimate_pi(convergence_criterion):\n", + " n = 0\n", + " d = 0\n", + " ratios = []\n", + "\n", + " while True:\n", + " x = random.random()\n", + " y = random.random()\n", + "\n", + " if x**2 + y**2 <= 1.0:\n", + " n += 1\n", + " d += 1\n", + " ratio = 4 * n / d\n", + " ratios.append(ratio)\n", + "\n", + " if abs(ratio - 3.141592653589793) / 3.141592653589793 <= convergence_criterion:\n", + " break\n", + "\n", + " return d, ratios\n", + "\n", + "convergence_criteria = [0.01, 0.001, 0.0001, 0.00001]\n", + "num_runs = 10\n", + "\n", + "for criterion in convergence_criteria:\n", + " draws_list = []\n", + "\n", + " for _ in range(num_runs):\n", + " num_draws, _ = estimate_pi(criterion)\n", + " draws_list.append(num_draws)\n", + "\n", + " avg_draws = statistics.mean(draws_list)\n", + " std_dev_draws = statistics.stdev(draws_list)\n", + "\n", + " print(f\"For convergence criterion {criterion}:\")\n", + " print(f\"Average number of draws: {avg_draws}\")\n", + " print(f\"Standard deviation of draws: {std_dev_draws}\")\n", + " print()\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "d5e87d54", + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "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.11.5" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +}