{ "cells": [ { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [], "source": [ "import mercury as mr\n", "import numpy as np\n", "import matplotlib.pyplot as plt\n", "%matplotlib inline" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "name = mr.Text(value=\"Piotr\", label=\"What is your name?\")\n", "print(f\"Hello {name.value}\")\n", "# set application properites with App object\n", "app = mr.App(show_code = True)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Consider one of the most basic problems:\n", "\n", "Finding the root of a function, i.e: $f(x) = 0$ .\n", "\n", "## Technique:\n", "\n", "We start with a boundary $[a,b]$ and then hope that there exists a point $p$ in that boundary where $f(p) = 0$. We half the end points of the boundary depending on if $f(a_i) \\text{ or } f(b_i)$ is negative or positive, until we reach the point $p$\n", "\n", "## Example\n", "Suppose we want to look for the zero for $f(x)= \\sin(x) + 0.5$ between $[-1,2]$. " ] }, { "cell_type": "code", "execution_count": 42, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "26\n" ] }, { "data": { "text/plain": [ "-0.523598775267601" ] }, "execution_count": 42, "metadata": {}, "output_type": "execute_result" } ], "source": [ "def f(x): \n", " return np.sin(x)+0.5\n", "\n", "def validate_interval(f,x0,x1):\n", " return f(x0)*f(x1) < 0\n", "\n", "\n", "def bisection(f, interval, n, tol):\n", " x0, x1 = interval[0], interval[1] #extract interval \n", " if not validate_interval(f, x0, x1): #check interval can be solved for roots\n", " return \"Not valid interval\"\n", "\n", " counter = 1\n", " while True:\n", " p = x0 + ((x1-x0)/2)\n", " y = f(p)\n", " if -tol < y < tol:\n", " print(counter)\n", " return p\n", " if validate_interval(f,x0,p):\n", " x1 = p\n", " else:\n", " x0 = p\n", " counter += 1\n", "\n", "\n", "\n", "bisection(f,[-1,2], 50, 0.000000001) " ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [], "source": [ "def graph(x):\n", " #need function\n", " #need tangents\n", " #root\n", " fig, ax = plt.subplots(figsize=(10, 10))\n", " y=f(x)\n", " plt.plot(x,y)\n", " \n", " plt.ylabel('some numbers')\n", " plt.axis('tight')\n", " plt.grid(True)\n", " plt.show()\n", " ax.spines['top'].set_visible(False)\n", " ax.spines['right'].set_visible(False)\n", "\n", "graph(np.arange(-np.pi,np.pi,np.pi/32))" ] }, { "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.10.13" }, "orig_nbformat": 4 }, "nbformat": 4, "nbformat_minor": 2 }