{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Using loops to calculate values using numerical methods" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "#Use a for loop to calculate the value of 1, using a numerical method\n", "n=0\n", "for i in range(1,5):\n", " n = n + 1/2**i\n", "print(f'The approx value of n is {n}')" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "n=0\n", "for i in range(1,10):\n", " n = n + 1/2**i\n", "print(f'The approx value of n is {n}')" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "The approx value of n is 1.0\n" ] } ], "source": [ "n=0\n", "for i in range(1,10000):\n", " n = n + 1/2**i\n", "print(f'The approx value of n is {n}')" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "The approx value of pi/4 is 0.8666666666666667\n" ] } ], "source": [ "n = 0\n", "for i in range(0,3):\n", " term = (-1)**i / (2*i+1)\n", " n = n + term\n", "print(f'The approx value of pi/4 is {n}')" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0.7853981633974483\n" ] } ], "source": [ "import math\n", "print(math.pi/4)" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "The approx value of pi/4 is 0.7604599047323508\n" ] } ], "source": [ "n = 0\n", "for i in range(0,10):\n", " term = (-1)**i / (2*i+1)\n", " n = n + term\n", "print(f'The approx value of pi/4 is {n}')" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "The approx value of pi/4 is 0.7853731633975086\n" ] } ], "source": [ "n = 0\n", "for i in range(0,10000):\n", " term = (-1)**i / (2*i+1)\n", " n = n + term\n", "print(f'The approx value of pi/4 is {n}')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "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.0" } }, "nbformat": 4, "nbformat_minor": 2 }