{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "## Homework Problem: Taylor Series e^x" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "from math import factorial\n", "factorial(1)" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "factorial(0)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Create the taylor series for e^x and keep running the series until the error is less than 0.001 compared to Python's math.exp() function" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Enter a number between 0 and 10: -1\n", "Enter a number between 0 and 10: 12\n", "Enter a number between 0 and 10: 2\n", "approximation: 7.3887125220458545\n", "using math.exp(): 7.38905609893065\n", "error: 0.0003435768847959153\n", "The loop ran 11 times\n" ] } ], "source": [ "from math import factorial, exp\n", "\n", "# validate user input, make them enter a number between 0 and 10\n", "\n", "# set input as invalid\n", "x = -1\n", "\n", "# while not (what you want):\n", "while not (x>=0 and x<=10):\n", " # ask for input\n", " x_str = input('Enter a number between 0 and 10: ')\n", " # run any code on the input\n", " x = float(x_str)\n", " \n", "approx = 0\n", "i=0\n", "while not (abs(exp(x)-approx)<0.001):\n", " try:\n", " term = (x**i)/(factorial(i))\n", " except:\n", " break\n", " approx = approx + term\n", " i = i + 1\n", "\n", "print(f'approximation: {approx}')\n", "print(f'using math.exp(): {exp(x)}')\n", "print(f'error: {abs(exp(x)-approx)}')\n", "print(f'The loop ran {i+1} times')" ] }, { "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 }