{ "cells": [ { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [], "source": [ "# Archimedes Method for PI\n", "# FB - 200912082\n", "# Revised by Bjorn.madsen AT operationsresearchgroup.com for Python3.3\n", "# BHM - 20130302\n", "\n", "import decimal\n", "\n", "def ArchPi(precision=99):\n", " # x: circumference of the circumscribed (outside) regular polygon\n", " # y: circumference of the inscribed (inside) regular polygon\n", "\n", " decimal.getcontext().prec = precision+1\n", " D=decimal.Decimal\n", " \n", " # max error allowed\n", " eps = D(1)/D(10**precision)\n", " \n", " # initialize w/ square\n", " x = D(4)\n", " y = D(2)*D(2).sqrt()\n", "\n", " ctr = D(0)\n", " while x-y > eps:\n", " xnew = 2*x*y/(x+y)\n", " y = D(xnew*y).sqrt()\n", " x = xnew\n", " ctr += 1\n", " \n", "\n", " return str((x+y)/D(2))\n" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "pi = 3.14159265358979323848\n" ] } ], "source": [ "PiA=ArchPi(20)\n", "print(\"pi =\",PiA)" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "3.141592653589793238462643383279502884197169399375105820974944592307816406286208998628034825342117068\n" ] } ], "source": [ "print(ArchPi(99))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "interpreter": { "hash": "64a7e88ebd0abc50aba166b172778bcdfbfd193da8f8e02bffc3c5f026b0d38a" }, "kernelspec": { "display_name": "Python 3.7.10", "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.7.10" }, "orig_nbformat": 4 }, "nbformat": 4, "nbformat_minor": 2 }