{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Symbolic Computation" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "data": { "text/html": [ "
" ], "text/plain": [ "" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import addutils.toc ; addutils.toc.js(ipy_notebook=True)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Symbolic computation (also called computer algebra) emphasizes exact computation where mathematical expressions and objects are represented by algebraic formulas, and not numbers. SymPy is the python module suitable for symbolic computation. See [Sympy Modules Reference](http://docs.sympy.org/dev/modules/index.html)." ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "\n" ], "text/plain": [ "" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from addutils import css_notebook\n", "from sympy import *\n", "import numpy as np\n", "import bokeh.plotting as bk\n", "from bokeh.plotting import output_notebook\n", "init_printing(use_latex='mathjax')\n", "css_notebook()" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "
\n", " \n", " Loading BokehJS ...\n", "
" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/javascript": [ "\n", "(function(root) {\n", " function now() {\n", " return new Date();\n", " }\n", "\n", " var force = true;\n", "\n", " if (typeof (root._bokeh_onload_callbacks) === \"undefined\" || force === true) {\n", " root._bokeh_onload_callbacks = [];\n", " root._bokeh_is_loading = undefined;\n", " }\n", "\n", " var JS_MIME_TYPE = 'application/javascript';\n", " var HTML_MIME_TYPE = 'text/html';\n", " var EXEC_MIME_TYPE = 'application/vnd.bokehjs_exec.v0+json';\n", " var CLASS_NAME = 'output_bokeh rendered_html';\n", "\n", " /**\n", " * Render data to the DOM node\n", " */\n", " function render(props, node) {\n", " var script = document.createElement(\"script\");\n", " node.appendChild(script);\n", " }\n", "\n", " /**\n", " * Handle when an output is cleared or removed\n", " */\n", " function handleClearOutput(event, handle) {\n", " var cell = handle.cell;\n", "\n", " var id = cell.output_area._bokeh_element_id;\n", " var server_id = cell.output_area._bokeh_server_id;\n", " // Clean up Bokeh references\n", " if (id !== undefined) {\n", " Bokeh.index[id].model.document.clear();\n", " delete Bokeh.index[id];\n", " }\n", "\n", " if (server_id !== undefined) {\n", " // Clean up Bokeh references\n", " var cmd = \"from bokeh.io.state import curstate; print(curstate().uuid_to_server['\" + server_id + \"'].get_sessions()[0].document.roots[0]._id)\";\n", " cell.notebook.kernel.execute(cmd, {\n", " iopub: {\n", " output: function(msg) {\n", " var element_id = msg.content.text.trim();\n", " Bokeh.index[element_id].model.document.clear();\n", " delete Bokeh.index[element_id];\n", " }\n", " }\n", " });\n", " // Destroy server and session\n", " var cmd = \"import bokeh.io.notebook as ion; ion.destroy_server('\" + server_id + \"')\";\n", " cell.notebook.kernel.execute(cmd);\n", " }\n", " }\n", "\n", " /**\n", " * Handle when a new output is added\n", " */\n", " function handleAddOutput(event, handle) {\n", " var output_area = handle.output_area;\n", " var output = handle.output;\n", "\n", " // limit handleAddOutput to display_data with EXEC_MIME_TYPE content only\n", " if ((output.output_type != \"display_data\") || (!output.data.hasOwnProperty(EXEC_MIME_TYPE))) {\n", " return\n", " }\n", "\n", " var toinsert = output_area.element.find(\".\" + CLASS_NAME.split(' ')[0]);\n", "\n", " if (output.metadata[EXEC_MIME_TYPE][\"id\"] !== undefined) {\n", " toinsert[0].firstChild.textContent = output.data[JS_MIME_TYPE];\n", " // store reference to embed id on output_area\n", " output_area._bokeh_element_id = output.metadata[EXEC_MIME_TYPE][\"id\"];\n", " }\n", " if (output.metadata[EXEC_MIME_TYPE][\"server_id\"] !== undefined) {\n", " var bk_div = document.createElement(\"div\");\n", " bk_div.innerHTML = output.data[HTML_MIME_TYPE];\n", " var script_attrs = bk_div.children[0].attributes;\n", " for (var i = 0; i < script_attrs.length; i++) {\n", " toinsert[0].firstChild.setAttribute(script_attrs[i].name, script_attrs[i].value);\n", " }\n", " // store reference to server id on output_area\n", " output_area._bokeh_server_id = output.metadata[EXEC_MIME_TYPE][\"server_id\"];\n", " }\n", " }\n", "\n", " function register_renderer(events, OutputArea) {\n", "\n", " function append_mime(data, metadata, element) {\n", " // create a DOM node to render to\n", " var toinsert = this.create_output_subarea(\n", " metadata,\n", " CLASS_NAME,\n", " EXEC_MIME_TYPE\n", " );\n", " this.keyboard_manager.register_events(toinsert);\n", " // Render to node\n", " var props = {data: data, metadata: metadata[EXEC_MIME_TYPE]};\n", " render(props, toinsert[0]);\n", " element.append(toinsert);\n", " return toinsert\n", " }\n", "\n", " /* Handle when an output is cleared or removed */\n", " events.on('clear_output.CodeCell', handleClearOutput);\n", " events.on('delete.Cell', handleClearOutput);\n", "\n", " /* Handle when a new output is added */\n", " events.on('output_added.OutputArea', handleAddOutput);\n", "\n", " /**\n", " * Register the mime type and append_mime function with output_area\n", " */\n", " OutputArea.prototype.register_mime_type(EXEC_MIME_TYPE, append_mime, {\n", " /* Is output safe? */\n", " safe: true,\n", " /* Index of renderer in `output_area.display_order` */\n", " index: 0\n", " });\n", " }\n", "\n", " // register the mime type if in Jupyter Notebook environment and previously unregistered\n", " if (root.Jupyter !== undefined) {\n", " var events = require('base/js/events');\n", " var OutputArea = require('notebook/js/outputarea').OutputArea;\n", "\n", " if (OutputArea.prototype.mime_types().indexOf(EXEC_MIME_TYPE) == -1) {\n", " register_renderer(events, OutputArea);\n", " }\n", " }\n", "\n", " \n", " if (typeof (root._bokeh_timeout) === \"undefined\" || force === true) {\n", " root._bokeh_timeout = Date.now() + 5000;\n", " root._bokeh_failed_load = false;\n", " }\n", "\n", " var NB_LOAD_WARNING = {'data': {'text/html':\n", " \"
\\n\"+\n", " \"

\\n\"+\n", " \"BokehJS does not appear to have successfully loaded. If loading BokehJS from CDN, this \\n\"+\n", " \"may be due to a slow or bad network connection. Possible fixes:\\n\"+\n", " \"

\\n\"+\n", " \"
    \\n\"+\n", " \"
  • re-rerun `output_notebook()` to attempt to load from CDN again, or
  • \\n\"+\n", " \"
  • use INLINE resources instead, as so:
  • \\n\"+\n", " \"
\\n\"+\n", " \"\\n\"+\n", " \"from bokeh.resources import INLINE\\n\"+\n", " \"output_notebook(resources=INLINE)\\n\"+\n", " \"\\n\"+\n", " \"
\"}};\n", "\n", " function display_loaded() {\n", " var el = document.getElementById(\"f0391b89-4ae5-49d9-81ca-de0649699f74\");\n", " if (el != null) {\n", " el.textContent = \"BokehJS is loading...\";\n", " }\n", " if (root.Bokeh !== undefined) {\n", " if (el != null) {\n", " el.textContent = \"BokehJS \" + root.Bokeh.version + \" successfully loaded.\";\n", " }\n", " } else if (Date.now() < root._bokeh_timeout) {\n", " setTimeout(display_loaded, 100)\n", " }\n", " }\n", "\n", "\n", " function run_callbacks() {\n", " try {\n", " root._bokeh_onload_callbacks.forEach(function(callback) { callback() });\n", " }\n", " finally {\n", " delete root._bokeh_onload_callbacks\n", " }\n", " console.info(\"Bokeh: all callbacks have finished\");\n", " }\n", "\n", " function load_libs(js_urls, callback) {\n", " root._bokeh_onload_callbacks.push(callback);\n", " if (root._bokeh_is_loading > 0) {\n", " console.log(\"Bokeh: BokehJS is being loaded, scheduling callback at\", now());\n", " return null;\n", " }\n", " if (js_urls == null || js_urls.length === 0) {\n", " run_callbacks();\n", " return null;\n", " }\n", " console.log(\"Bokeh: BokehJS not loaded, scheduling load and callback at\", now());\n", " root._bokeh_is_loading = js_urls.length;\n", " for (var i = 0; i < js_urls.length; i++) {\n", " var url = js_urls[i];\n", " var s = document.createElement('script');\n", " s.src = url;\n", " s.async = false;\n", " s.onreadystatechange = s.onload = function() {\n", " root._bokeh_is_loading--;\n", " if (root._bokeh_is_loading === 0) {\n", " console.log(\"Bokeh: all BokehJS libraries loaded\");\n", " run_callbacks()\n", " }\n", " };\n", " s.onerror = function() {\n", " console.warn(\"failed to load library \" + url);\n", " };\n", " console.log(\"Bokeh: injecting script tag for BokehJS library: \", url);\n", " document.getElementsByTagName(\"head\")[0].appendChild(s);\n", " }\n", " };var element = document.getElementById(\"f0391b89-4ae5-49d9-81ca-de0649699f74\");\n", " if (element == null) {\n", " console.log(\"Bokeh: ERROR: autoload.js configured with elementid 'f0391b89-4ae5-49d9-81ca-de0649699f74' but no matching script tag was found. \")\n", " return false;\n", " }\n", "\n", " var js_urls = [\"https://cdn.pydata.org/bokeh/release/bokeh-0.12.13.min.js\", \"https://cdn.pydata.org/bokeh/release/bokeh-widgets-0.12.13.min.js\", \"https://cdn.pydata.org/bokeh/release/bokeh-tables-0.12.13.min.js\", \"https://cdn.pydata.org/bokeh/release/bokeh-gl-0.12.13.min.js\"];\n", "\n", " var inline_js = [\n", " function(Bokeh) {\n", " Bokeh.set_log_level(\"info\");\n", " },\n", " \n", " function(Bokeh) {\n", " \n", " },\n", " function(Bokeh) {\n", " console.log(\"Bokeh: injecting CSS: https://cdn.pydata.org/bokeh/release/bokeh-0.12.13.min.css\");\n", " Bokeh.embed.inject_css(\"https://cdn.pydata.org/bokeh/release/bokeh-0.12.13.min.css\");\n", " console.log(\"Bokeh: injecting CSS: https://cdn.pydata.org/bokeh/release/bokeh-widgets-0.12.13.min.css\");\n", " Bokeh.embed.inject_css(\"https://cdn.pydata.org/bokeh/release/bokeh-widgets-0.12.13.min.css\");\n", " console.log(\"Bokeh: injecting CSS: https://cdn.pydata.org/bokeh/release/bokeh-tables-0.12.13.min.css\");\n", " Bokeh.embed.inject_css(\"https://cdn.pydata.org/bokeh/release/bokeh-tables-0.12.13.min.css\");\n", " }\n", " ];\n", "\n", " function run_inline_js() {\n", " \n", " if ((root.Bokeh !== undefined) || (force === true)) {\n", " for (var i = 0; i < inline_js.length; i++) {\n", " inline_js[i].call(root, root.Bokeh);\n", " }if (force === true) {\n", " display_loaded();\n", " }} else if (Date.now() < root._bokeh_timeout) {\n", " setTimeout(run_inline_js, 100);\n", " } else if (!root._bokeh_failed_load) {\n", " console.log(\"Bokeh: BokehJS failed to load within specified timeout.\");\n", " root._bokeh_failed_load = true;\n", " } else if (force !== true) {\n", " var cell = $(document.getElementById(\"f0391b89-4ae5-49d9-81ca-de0649699f74\")).parents('.cell').data().cell;\n", " cell.output_area.append_execute_result(NB_LOAD_WARNING)\n", " }\n", "\n", " }\n", "\n", " if (root._bokeh_is_loading === 0) {\n", " console.log(\"Bokeh: BokehJS loaded, going straight to plotting\");\n", " run_inline_js();\n", " } else {\n", " load_libs(js_urls, function() {\n", " console.log(\"Bokeh: BokehJS plotting callback run at\", now());\n", " run_inline_js();\n", " });\n", " }\n", "}(window));" ], "application/vnd.bokehjs_load.v0+json": "\n(function(root) {\n function now() {\n return new Date();\n }\n\n var force = true;\n\n if (typeof (root._bokeh_onload_callbacks) === \"undefined\" || force === true) {\n root._bokeh_onload_callbacks = [];\n root._bokeh_is_loading = undefined;\n }\n\n \n\n \n if (typeof (root._bokeh_timeout) === \"undefined\" || force === true) {\n root._bokeh_timeout = Date.now() + 5000;\n root._bokeh_failed_load = false;\n }\n\n var NB_LOAD_WARNING = {'data': {'text/html':\n \"
\\n\"+\n \"

\\n\"+\n \"BokehJS does not appear to have successfully loaded. If loading BokehJS from CDN, this \\n\"+\n \"may be due to a slow or bad network connection. Possible fixes:\\n\"+\n \"

\\n\"+\n \"
    \\n\"+\n \"
  • re-rerun `output_notebook()` to attempt to load from CDN again, or
  • \\n\"+\n \"
  • use INLINE resources instead, as so:
  • \\n\"+\n \"
\\n\"+\n \"\\n\"+\n \"from bokeh.resources import INLINE\\n\"+\n \"output_notebook(resources=INLINE)\\n\"+\n \"\\n\"+\n \"
\"}};\n\n function display_loaded() {\n var el = document.getElementById(\"f0391b89-4ae5-49d9-81ca-de0649699f74\");\n if (el != null) {\n el.textContent = \"BokehJS is loading...\";\n }\n if (root.Bokeh !== undefined) {\n if (el != null) {\n el.textContent = \"BokehJS \" + root.Bokeh.version + \" successfully loaded.\";\n }\n } else if (Date.now() < root._bokeh_timeout) {\n setTimeout(display_loaded, 100)\n }\n }\n\n\n function run_callbacks() {\n try {\n root._bokeh_onload_callbacks.forEach(function(callback) { callback() });\n }\n finally {\n delete root._bokeh_onload_callbacks\n }\n console.info(\"Bokeh: all callbacks have finished\");\n }\n\n function load_libs(js_urls, callback) {\n root._bokeh_onload_callbacks.push(callback);\n if (root._bokeh_is_loading > 0) {\n console.log(\"Bokeh: BokehJS is being loaded, scheduling callback at\", now());\n return null;\n }\n if (js_urls == null || js_urls.length === 0) {\n run_callbacks();\n return null;\n }\n console.log(\"Bokeh: BokehJS not loaded, scheduling load and callback at\", now());\n root._bokeh_is_loading = js_urls.length;\n for (var i = 0; i < js_urls.length; i++) {\n var url = js_urls[i];\n var s = document.createElement('script');\n s.src = url;\n s.async = false;\n s.onreadystatechange = s.onload = function() {\n root._bokeh_is_loading--;\n if (root._bokeh_is_loading === 0) {\n console.log(\"Bokeh: all BokehJS libraries loaded\");\n run_callbacks()\n }\n };\n s.onerror = function() {\n console.warn(\"failed to load library \" + url);\n };\n console.log(\"Bokeh: injecting script tag for BokehJS library: \", url);\n document.getElementsByTagName(\"head\")[0].appendChild(s);\n }\n };var element = document.getElementById(\"f0391b89-4ae5-49d9-81ca-de0649699f74\");\n if (element == null) {\n console.log(\"Bokeh: ERROR: autoload.js configured with elementid 'f0391b89-4ae5-49d9-81ca-de0649699f74' but no matching script tag was found. \")\n return false;\n }\n\n var js_urls = [\"https://cdn.pydata.org/bokeh/release/bokeh-0.12.13.min.js\", \"https://cdn.pydata.org/bokeh/release/bokeh-widgets-0.12.13.min.js\", \"https://cdn.pydata.org/bokeh/release/bokeh-tables-0.12.13.min.js\", \"https://cdn.pydata.org/bokeh/release/bokeh-gl-0.12.13.min.js\"];\n\n var inline_js = [\n function(Bokeh) {\n Bokeh.set_log_level(\"info\");\n },\n \n function(Bokeh) {\n \n },\n function(Bokeh) {\n console.log(\"Bokeh: injecting CSS: https://cdn.pydata.org/bokeh/release/bokeh-0.12.13.min.css\");\n Bokeh.embed.inject_css(\"https://cdn.pydata.org/bokeh/release/bokeh-0.12.13.min.css\");\n console.log(\"Bokeh: injecting CSS: https://cdn.pydata.org/bokeh/release/bokeh-widgets-0.12.13.min.css\");\n Bokeh.embed.inject_css(\"https://cdn.pydata.org/bokeh/release/bokeh-widgets-0.12.13.min.css\");\n console.log(\"Bokeh: injecting CSS: https://cdn.pydata.org/bokeh/release/bokeh-tables-0.12.13.min.css\");\n Bokeh.embed.inject_css(\"https://cdn.pydata.org/bokeh/release/bokeh-tables-0.12.13.min.css\");\n }\n ];\n\n function run_inline_js() {\n \n if ((root.Bokeh !== undefined) || (force === true)) {\n for (var i = 0; i < inline_js.length; i++) {\n inline_js[i].call(root, root.Bokeh);\n }if (force === true) {\n display_loaded();\n }} else if (Date.now() < root._bokeh_timeout) {\n setTimeout(run_inline_js, 100);\n } else if (!root._bokeh_failed_load) {\n console.log(\"Bokeh: BokehJS failed to load within specified timeout.\");\n root._bokeh_failed_load = true;\n } else if (force !== true) {\n var cell = $(document.getElementById(\"f0391b89-4ae5-49d9-81ca-de0649699f74\")).parents('.cell').data().cell;\n cell.output_area.append_execute_result(NB_LOAD_WARNING)\n }\n\n }\n\n if (root._bokeh_is_loading === 0) {\n console.log(\"Bokeh: BokehJS loaded, going straight to plotting\");\n run_inline_js();\n } else {\n load_libs(js_urls, function() {\n console.log(\"Bokeh: BokehJS plotting callback run at\", now());\n run_inline_js();\n });\n }\n}(window));" }, "metadata": {}, "output_type": "display_data" } ], "source": [ "output_notebook()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 1 Basic manipulation" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "data": { "text/latex": [ "$$\\pi \\left(3 a b^{2}\\right)^{c}$$" ], "text/plain": [ " c\n", " ⎛ 2⎞ \n", "π⋅⎝3⋅a⋅b ⎠ " ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a, b, c = symbols('a, b, c')\n", "exp1 = pi*( a*b*b+2*b*a*b )**c\n", "exp1" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can add assumpions to symbols" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "data": { "text/latex": [ "$$\\mathrm{True}$$" ], "text/plain": [ "True" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "k = symbols('k', real=True, positive=True)\n", "k > 0" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Rational numbers" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "data": { "text/latex": [ "$$\\frac{19}{6}$$" ], "text/plain": [ "19/6" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "r1 = Rational(5,6)\n", "r2 = Rational(7,3)\n", "r1+r2" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The expression may be calculated by substituting numerical values to given variables (in this case --> a,b):" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "data": { "text/latex": [ "$$0.0824479576008105$$" ], "text/plain": [ "0.0824479576008105" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "exp1.evalf(subs={a:6e-3, b:3, c:2})" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We can combine expressions and Numpy arrays" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "
\n", "
\n", "
" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/javascript": [ "(function(root) {\n", " function embed_document(root) {\n", " \n", " var docs_json = {\"d8420af6-659c-4a24-b861-9b0f3ba10268\":{\"roots\":{\"references\":[{\"attributes\":{\"line_color\":\"#1f77b4\",\"x\":{\"field\":\"x\"},\"y\":{\"field\":\"y\"}},\"id\":\"f91df7a5-2fd4-45b4-8900-489a820534c7\",\"type\":\"Line\"},{\"attributes\":{},\"id\":\"9963c5a3-e727-492a-85b7-d1109858b707\",\"type\":\"WheelZoomTool\"},{\"attributes\":{\"callback\":null},\"id\":\"034cc315-9f16-46a8-8e98-d03659409190\",\"type\":\"DataRange1d\"},{\"attributes\":{\"overlay\":{\"id\":\"8d6b7f4b-53d9-46a7-a026-b70bb50fdbf3\",\"type\":\"BoxAnnotation\"}},\"id\":\"96d39ae9-e7ae-465a-99e6-39e452796a81\",\"type\":\"BoxZoomTool\"},{\"attributes\":{},\"id\":\"6be6f5b2-fccb-4e48-b205-01b9d92b2c99\",\"type\":\"SaveTool\"},{\"attributes\":{},\"id\":\"fcc63b06-0b68-4f1a-b045-eb5e385e050a\",\"type\":\"LinearScale\"},{\"attributes\":{},\"id\":\"16e41686-90e6-4aea-8d1d-83bbb24420df\",\"type\":\"BasicTickFormatter\"},{\"attributes\":{},\"id\":\"ca6ace25-d95e-45bd-a9c4-266095150a52\",\"type\":\"BasicTickFormatter\"},{\"attributes\":{},\"id\":\"6d7fe93d-a31e-4f0e-9391-a13bd13096e6\",\"type\":\"ResetTool\"},{\"attributes\":{\"callback\":null},\"id\":\"441934d5-2733-4faa-b68f-26cda4f41e4a\",\"type\":\"DataRange1d\"},{\"attributes\":{},\"id\":\"641aeb93-e2c2-4279-8456-f943762bfb24\",\"type\":\"HelpTool\"},{\"attributes\":{},\"id\":\"658489a7-3adc-4b93-bb62-7134e51423fa\",\"type\":\"LinearScale\"},{\"attributes\":{\"formatter\":{\"id\":\"16e41686-90e6-4aea-8d1d-83bbb24420df\",\"type\":\"BasicTickFormatter\"},\"plot\":{\"id\":\"0b7ece2c-0736-4988-a7a3-b323c2d0058b\",\"subtype\":\"Figure\",\"type\":\"Plot\"},\"ticker\":{\"id\":\"4e558a01-26a9-49f9-bcda-1b2720a53990\",\"type\":\"BasicTicker\"}},\"id\":\"e8ab2133-fe13-4626-bd53-e9cda2913202\",\"type\":\"LinearAxis\"},{\"attributes\":{\"data_source\":{\"id\":\"b7a9c9d6-e3b6-4f13-94da-2cde7e14733d\",\"type\":\"ColumnDataSource\"},\"glyph\":{\"id\":\"f91df7a5-2fd4-45b4-8900-489a820534c7\",\"type\":\"Line\"},\"hover_glyph\":null,\"muted_glyph\":null,\"nonselection_glyph\":{\"id\":\"cf714d7a-30b6-4ca3-8156-4ae95292b343\",\"type\":\"Line\"},\"selection_glyph\":null,\"view\":{\"id\":\"a04c6498-790b-41ce-ad0d-7e4acae2e1d8\",\"type\":\"CDSView\"}},\"id\":\"649f86f9-286f-4254-a82a-b509daf31ad5\",\"type\":\"GlyphRenderer\"},{\"attributes\":{\"source\":{\"id\":\"b7a9c9d6-e3b6-4f13-94da-2cde7e14733d\",\"type\":\"ColumnDataSource\"}},\"id\":\"a04c6498-790b-41ce-ad0d-7e4acae2e1d8\",\"type\":\"CDSView\"},{\"attributes\":{},\"id\":\"4e558a01-26a9-49f9-bcda-1b2720a53990\",\"type\":\"BasicTicker\"},{\"attributes\":{\"below\":[{\"id\":\"e8ab2133-fe13-4626-bd53-e9cda2913202\",\"type\":\"LinearAxis\"}],\"left\":[{\"id\":\"93312335-c605-4dcf-95e9-72246f8897f7\",\"type\":\"LinearAxis\"}],\"renderers\":[{\"id\":\"e8ab2133-fe13-4626-bd53-e9cda2913202\",\"type\":\"LinearAxis\"},{\"id\":\"305fe361-d9ca-4bfd-a742-6236bae94d02\",\"type\":\"Grid\"},{\"id\":\"93312335-c605-4dcf-95e9-72246f8897f7\",\"type\":\"LinearAxis\"},{\"id\":\"26cefec3-4052-47b0-81e4-7e2072755e27\",\"type\":\"Grid\"},{\"id\":\"8d6b7f4b-53d9-46a7-a026-b70bb50fdbf3\",\"type\":\"BoxAnnotation\"},{\"id\":\"649f86f9-286f-4254-a82a-b509daf31ad5\",\"type\":\"GlyphRenderer\"}],\"title\":null,\"toolbar\":{\"id\":\"0c54e254-ed47-43b9-b2bc-721c47be6dd3\",\"type\":\"Toolbar\"},\"x_range\":{\"id\":\"034cc315-9f16-46a8-8e98-d03659409190\",\"type\":\"DataRange1d\"},\"x_scale\":{\"id\":\"fcc63b06-0b68-4f1a-b045-eb5e385e050a\",\"type\":\"LinearScale\"},\"y_range\":{\"id\":\"441934d5-2733-4faa-b68f-26cda4f41e4a\",\"type\":\"DataRange1d\"},\"y_scale\":{\"id\":\"658489a7-3adc-4b93-bb62-7134e51423fa\",\"type\":\"LinearScale\"}},\"id\":\"0b7ece2c-0736-4988-a7a3-b323c2d0058b\",\"subtype\":\"Figure\",\"type\":\"Plot\"},{\"attributes\":{\"plot\":{\"id\":\"0b7ece2c-0736-4988-a7a3-b323c2d0058b\",\"subtype\":\"Figure\",\"type\":\"Plot\"},\"ticker\":{\"id\":\"4e558a01-26a9-49f9-bcda-1b2720a53990\",\"type\":\"BasicTicker\"}},\"id\":\"305fe361-d9ca-4bfd-a742-6236bae94d02\",\"type\":\"Grid\"},{\"attributes\":{\"formatter\":{\"id\":\"ca6ace25-d95e-45bd-a9c4-266095150a52\",\"type\":\"BasicTickFormatter\"},\"plot\":{\"id\":\"0b7ece2c-0736-4988-a7a3-b323c2d0058b\",\"subtype\":\"Figure\",\"type\":\"Plot\"},\"ticker\":{\"id\":\"7b1ad4d3-822d-4a14-977f-0222582e1fd7\",\"type\":\"BasicTicker\"}},\"id\":\"93312335-c605-4dcf-95e9-72246f8897f7\",\"type\":\"LinearAxis\"},{\"attributes\":{},\"id\":\"7b1ad4d3-822d-4a14-977f-0222582e1fd7\",\"type\":\"BasicTicker\"},{\"attributes\":{\"dimension\":1,\"plot\":{\"id\":\"0b7ece2c-0736-4988-a7a3-b323c2d0058b\",\"subtype\":\"Figure\",\"type\":\"Plot\"},\"ticker\":{\"id\":\"7b1ad4d3-822d-4a14-977f-0222582e1fd7\",\"type\":\"BasicTicker\"}},\"id\":\"26cefec3-4052-47b0-81e4-7e2072755e27\",\"type\":\"Grid\"},{\"attributes\":{\"callback\":null,\"column_names\":[\"x\",\"y\"],\"data\":{\"x\":{\"__ndarray__\":\"AAAAAAAAAACamZmZmZm5P5qZmZmZmck/NDMzMzMz0z+amZmZmZnZPwAAAAAAAOA/NDMzMzMz4z9nZmZmZmbmP5qZmZmZmek/zczMzMzM7D8AAAAAAADwP5qZmZmZmfE/NDMzMzMz8z/NzMzMzMz0P2dmZmZmZvY/AAAAAAAA+D+amZmZmZn5PzQzMzMzM/s/zczMzMzM/D9nZmZmZmb+PwAAAAAAAABAzczMzMzMAECamZmZmZkBQGdmZmZmZgJANDMzMzMzA0AAAAAAAAAEQM3MzMzMzARAmpmZmZmZBUBnZmZmZmYGQDQzMzMzMwdAAAAAAAAACEDNzMzMzMwIQJqZmZmZmQlAZ2ZmZmZmCkA0MzMzMzMLQAAAAAAAAAxAzczMzMzMDECamZmZmZkNQGdmZmZmZg5ANDMzMzMzD0AAAAAAAAAQQGdmZmZmZhBAzczMzMzMEEAzMzMzMzMRQJqZmZmZmRFAAAAAAAAAEkBnZmZmZmYSQM3MzMzMzBJANDMzMzMzE0CamZmZmZkTQAAAAAAAABRAZ2ZmZmZmFEDNzMzMzMwUQDQzMzMzMxVAmpmZmZmZFUAAAAAAAAAWQGdmZmZmZhZAzczMzMzMFkA0MzMzMzMXQJqZmZmZmRdAAAAAAAAAGEBnZmZmZmYYQM3MzMzMzBhANDMzMzMzGUCamZmZmZkZQAAAAAAAABpAZ2ZmZmZmGkDNzMzMzMwaQDQzMzMzMxtAmpmZmZmZG0AAAAAAAAAcQGdmZmZmZhxAzczMzMzMHEA0MzMzMzMdQJqZmZmZmR1AAAAAAAAAHkBnZmZmZmYeQM3MzMzMzB5ANDMzMzMzH0CamZmZmZkfQAAAAAAAACBAMzMzMzMzIEBnZmZmZmYgQJqZmZmZmSBAzczMzMzMIEAAAAAAAAAhQDMzMzMzMyFAZ2ZmZmZmIUCamZmZmZkhQM3MzMzMzCFAAAAAAAAAIkAzMzMzMzMiQGdmZmZmZiJAmpmZmZmZIkDNzMzMzMwiQAAAAAAAACNANDMzMzMzI0BnZmZmZmYjQJqZmZmZmSNAzczMzMzMI0A=\",\"dtype\":\"float64\",\"shape\":[100]},\"y\":{\"__ndarray__\":\"AAAAAAAAAAB02VRuylJ7PnTZVG7KUrs+nbHRGWRK4T502VRuylL7PrhJ1w1IrRA/nbHRGWRKIT+7nEzJNwQwP3TZVG7KUjs/xWStsCbiRT+4SdcNSK1QP6IKQK2nalg/nbHRGWRKYT+skP5Uv9BnP7WcTMk3BHA/TXmEMU8bdT902VRuylJ7PzsI8+YuaYE/xWStsCbihT/8A2h+tiqLP7hJ1w1IrZA/U/bEmlZFlD+iCkCtp2qYP18fSv3/Kp0/nbHRGWRKoT99TeV0hlukP6yQ/lS/0Kc/jnOb9ziyqz+7nEzJNwSwP1c4GqoYbrI/TXmEMU8btT/F8QhvlBC4P3TZVG7KUrs/eg1FN/zmvj87CPPmLmnBP00FOhkmjcM/xWStsCbixT894JopCGvIPwMEaH62Kss/IS+SJzIkzj+4SdcNSK3QP8Aated8aNI/U/bEmlZF1D+CMXVffkXWP6IKQK2natg/hamrOpC22j9SH0r9/yrdP5JmuSnJyd8/nbHRGWRK4T878d7m8cbiP31N5XSGW+Q/Z5ZLXB8J5j+skP5Uv9DnP7j1cDZus+k/jnOb9ziy6z/4rPyuMc7tP7WcTMk3BPA/hNL9ewcx8T9XOBqqGG7yP+UI7Z3+u/M/TXmEMU8b9T//uLHOooz2P8XxCG+UEPg/yUfhm8Gn+T902VRuylL7P56/QI9REv0/cQ1FN/zm/j82aGIXuWgAQDsI8+YuaQFA1edI/jV1AkBNBToZJo0DQBPcfTtYsQRAxWStsCbiBUAwFUMM7R8HQD3gmikIawhAEjbyK9bDCUD8A2h+tioLQHK0/NMJoAxAIS+SJzIkDkDJ2Ou7krcPQLhJ1w1IrRBAIl+wDMiGEUDAGrXnfGgSQGUpCtCaUhNAU/bEmlZFFECKq+vA5UAVQIIxdV9+RRZASS9JN1dTF0CiCkCtp2oYQLvnIsqnixlAhamrOpC2GkBk8YRPmusbQFIfSv3/Kh1ABFKH3Pt0HkCSZrkpyckfQG/8puLRlCBAnbHRGWRKIUBFX4TOuQUiQDvx3ubxxiJAf7L5miuOI0A=\",\"dtype\":\"float64\",\"shape\":[100]}}},\"id\":\"b7a9c9d6-e3b6-4f13-94da-2cde7e14733d\",\"type\":\"ColumnDataSource\"},{\"attributes\":{\"line_alpha\":0.1,\"line_color\":\"#1f77b4\",\"x\":{\"field\":\"x\"},\"y\":{\"field\":\"y\"}},\"id\":\"cf714d7a-30b6-4ca3-8156-4ae95292b343\",\"type\":\"Line\"},{\"attributes\":{\"bottom_units\":\"screen\",\"fill_alpha\":{\"value\":0.5},\"fill_color\":{\"value\":\"lightgrey\"},\"left_units\":\"screen\",\"level\":\"overlay\",\"line_alpha\":{\"value\":1.0},\"line_color\":{\"value\":\"black\"},\"line_dash\":[4,4],\"line_width\":{\"value\":2},\"plot\":null,\"render_mode\":\"css\",\"right_units\":\"screen\",\"top_units\":\"screen\"},\"id\":\"8d6b7f4b-53d9-46a7-a026-b70bb50fdbf3\",\"type\":\"BoxAnnotation\"},{\"attributes\":{},\"id\":\"b0c9c98f-10ba-45ae-accc-197d456ab418\",\"type\":\"PanTool\"},{\"attributes\":{\"active_drag\":\"auto\",\"active_inspect\":\"auto\",\"active_scroll\":\"auto\",\"active_tap\":\"auto\",\"tools\":[{\"id\":\"b0c9c98f-10ba-45ae-accc-197d456ab418\",\"type\":\"PanTool\"},{\"id\":\"9963c5a3-e727-492a-85b7-d1109858b707\",\"type\":\"WheelZoomTool\"},{\"id\":\"96d39ae9-e7ae-465a-99e6-39e452796a81\",\"type\":\"BoxZoomTool\"},{\"id\":\"6be6f5b2-fccb-4e48-b205-01b9d92b2c99\",\"type\":\"SaveTool\"},{\"id\":\"6d7fe93d-a31e-4f0e-9391-a13bd13096e6\",\"type\":\"ResetTool\"},{\"id\":\"641aeb93-e2c2-4279-8456-f943762bfb24\",\"type\":\"HelpTool\"}]},\"id\":\"0c54e254-ed47-43b9-b2bc-721c47be6dd3\",\"type\":\"Toolbar\"}],\"root_ids\":[\"0b7ece2c-0736-4988-a7a3-b323c2d0058b\"]},\"title\":\"Bokeh Application\",\"version\":\"0.12.13\"}};\n", " var render_items = [{\"docid\":\"d8420af6-659c-4a24-b861-9b0f3ba10268\",\"elementid\":\"5d35db8a-4e96-4ee8-9b05-75cb04fc0f54\",\"modelid\":\"0b7ece2c-0736-4988-a7a3-b323c2d0058b\"}];\n", " root.Bokeh.embed.embed_items_notebook(docs_json, render_items);\n", "\n", " }\n", " if (root.Bokeh !== undefined) {\n", " embed_document(root);\n", " } else {\n", " var attempts = 0;\n", " var timer = setInterval(function(root) {\n", " if (root.Bokeh !== undefined) {\n", " embed_document(root);\n", " clearInterval(timer);\n", " }\n", " attempts++;\n", " if (attempts > 100) {\n", " console.log(\"Bokeh: ERROR: Unable to run BokehJS code because BokehJS library is missing\")\n", " clearInterval(timer);\n", " }\n", " }, 10, root)\n", " }\n", "})(window);" ], "application/vnd.bokehjs_exec.v0+json": "" }, "metadata": { "application/vnd.bokehjs_exec.v0+json": { "id": "0b7ece2c-0736-4988-a7a3-b323c2d0058b" } }, "output_type": "display_data" } ], "source": [ "b_vec = np.arange(0, 10, 0.1)\n", "y_vec = np.array([exp1.evalf(subs={a:6e-3, b:bb, c:2}) for bb in b_vec])\n", "y_vec = np.float64(y_vec)\n", "fig = bk.figure(title=None)\n", "fig.line(b_vec, y_vec)\n", "bk.show(fig)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "However, this kind of numerical evolution can be very slow, and there is a much more efficient way to do it: Use the function `lambdify` to \"compile\" a Sympy expression into a function that is much more efficient to evaluate numerically:" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [], "source": [ "f = lambdify([b], exp1, 'numpy')\n", "y_vec = f(b_vec)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 2 Solve" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Algebraically solve equations or systems of equations (expr = 0)" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "data": { "text/latex": [ "$$42.0 x + 40 y - 2.0 z$$" ], "text/plain": [ "42.0⋅x + 40⋅y - 2.0⋅z" ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "x, y, z = symbols(\"x y z\")\n", "e = (x+y)*40-(z-x)/0.5\n", "e" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "data": { "text/latex": [ "$$\\left [ \\left \\{ x : - 0.952380952380952 y + 0.0476190476190476 z\\right \\}\\right ]$$" ], "text/plain": [ "[{x: -0.952380952380952⋅y + 0.0476190476190476⋅z}]" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ "solve(e)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 3 Algebra" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 3.1 Expand and Factor" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "data": { "text/latex": [ "$$\\left(x + 1\\right) \\sin{\\left (x + 2 \\right )} \\tanh{\\left (x + 3 \\right )}$$" ], "text/plain": [ "(x + 1)⋅sin(x + 2)⋅tanh(x + 3)" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "exp2 = (x+1)*sin(x+2)*tanh(x+3)\n", "exp2" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "data": { "text/latex": [ "$$x \\sin{\\left (x + 2 \\right )} \\tanh{\\left (x + 3 \\right )} + \\sin{\\left (x + 2 \\right )} \\tanh{\\left (x + 3 \\right )}$$" ], "text/plain": [ "x⋅sin(x + 2)⋅tanh(x + 3) + sin(x + 2)⋅tanh(x + 3)" ] }, "execution_count": 13, "metadata": {}, "output_type": "execute_result" } ], "source": [ "expand(exp2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The `expand` function takes a number of keywords arguments which we can tell the functions what kind of expansions we want to have performed. For example, to expand trigonometric expressions, use the `trig=True` keyword argument (see `help(sym.expand)` for more info):" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "data": { "text/latex": [ "$$- x \\sin{\\left (x \\right )} \\tanh{\\left (x + 3 \\right )} + 2 x \\sin{\\left (x \\right )} \\cos^{2}{\\left (1 \\right )} \\tanh{\\left (x + 3 \\right )} + 2 x \\sin{\\left (1 \\right )} \\cos{\\left (1 \\right )} \\cos{\\left (x \\right )} \\tanh{\\left (x + 3 \\right )} - \\sin{\\left (x \\right )} \\tanh{\\left (x + 3 \\right )} + 2 \\sin{\\left (x \\right )} \\cos^{2}{\\left (1 \\right )} \\tanh{\\left (x + 3 \\right )} + 2 \\sin{\\left (1 \\right )} \\cos{\\left (1 \\right )} \\cos{\\left (x \\right )} \\tanh{\\left (x + 3 \\right )}$$" ], "text/plain": [ " 2 \n", "-x⋅sin(x)⋅tanh(x + 3) + 2⋅x⋅sin(x)⋅cos (1)⋅tanh(x + 3) + 2⋅x⋅sin(1)⋅cos(1)⋅cos\n", "\n", " 2 \n", "(x)⋅tanh(x + 3) - sin(x)⋅tanh(x + 3) + 2⋅sin(x)⋅cos (1)⋅tanh(x + 3) + 2⋅sin(1)\n", "\n", " \n", "⋅cos(1)⋅cos(x)⋅tanh(x + 3)" ] }, "execution_count": 14, "metadata": {}, "output_type": "execute_result" } ], "source": [ "expand(exp2, trig=True)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The opposite a product expansion is of course factoring. The factor an expression in SymPy use the `factor` function: " ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "data": { "text/latex": [ "$$\\left(x + 1\\right) \\left(x + 2\\right) \\left(x + 3\\right)$$" ], "text/plain": [ "(x + 1)⋅(x + 2)⋅(x + 3)" ] }, "execution_count": 15, "metadata": {}, "output_type": "execute_result" } ], "source": [ "factor(x**3 + 6 * x**2 + 11*x + 6)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 3.2 Symplify" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The `simplify` tries to simplify an expression into a nice looking expression, using various techniques. More specific alternatives to the `simplify` functions also exists: `trigsimp`, `powsimp`, `logcombine`, etc. \n", "\n", "The basic usages of these functions are as follows:" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "data": { "text/latex": [ "$$1$$" ], "text/plain": [ "1" ] }, "execution_count": 16, "metadata": {}, "output_type": "execute_result" } ], "source": [ "simplify(sin(x)**2 + cos(x)**2)" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [ { "data": { "text/latex": [ "$$\\tan{\\left (x \\right )}$$" ], "text/plain": [ "tan(x)" ] }, "execution_count": 17, "metadata": {}, "output_type": "execute_result" } ], "source": [ "simplify(sin(x)/cos(x))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 3.3 apart and together" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [ { "data": { "text/latex": [ "$$\\frac{1}{\\left(a + 1\\right) \\left(a + 2\\right)}$$" ], "text/plain": [ " 1 \n", "───────────────\n", "(a + 1)⋅(a + 2)" ] }, "execution_count": 18, "metadata": {}, "output_type": "execute_result" } ], "source": [ "exp3 = 1/((a+1)*(a+2))\n", "exp3" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [ { "data": { "text/latex": [ "$$- \\frac{1}{a + 2} + \\frac{1}{a + 1}$$" ], "text/plain": [ " 1 1 \n", "- ───── + ─────\n", " a + 2 a + 1" ] }, "execution_count": 19, "metadata": {}, "output_type": "execute_result" } ], "source": [ "apart(exp3)" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "data": { "text/latex": [ "$$\\frac{1}{a + 3} + \\frac{1}{a + 2}$$" ], "text/plain": [ " 1 1 \n", "───── + ─────\n", "a + 3 a + 2" ] }, "execution_count": 20, "metadata": {}, "output_type": "execute_result" } ], "source": [ "exp4 = 1/(a+2) + 1/(a+3)\n", "exp4" ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [ { "data": { "text/latex": [ "$$\\frac{2 a + 5}{\\left(a + 2\\right) \\left(a + 3\\right)}$$" ], "text/plain": [ " 2⋅a + 5 \n", "───────────────\n", "(a + 2)⋅(a + 3)" ] }, "execution_count": 21, "metadata": {}, "output_type": "execute_result" } ], "source": [ "together(exp4)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 4 Calculus" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 4.1 Differentiation and Integration" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [ { "data": { "text/latex": [ "$$\\left(x + 1\\right) \\sin{\\left (x + 2 \\right )} \\tanh{\\left (x + 3 \\right )}$$" ], "text/plain": [ "(x + 1)⋅sin(x + 2)⋅tanh(x + 3)" ] }, "execution_count": 22, "metadata": {}, "output_type": "execute_result" } ], "source": [ "exp2" ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [ { "data": { "text/latex": [ "$$\\left(x + 1\\right) \\left(- \\tanh^{2}{\\left (x + 3 \\right )} + 1\\right) \\sin{\\left (x + 2 \\right )} + \\left(x + 1\\right) \\cos{\\left (x + 2 \\right )} \\tanh{\\left (x + 3 \\right )} + \\sin{\\left (x + 2 \\right )} \\tanh{\\left (x + 3 \\right )}$$" ], "text/plain": [ " ⎛ 2 ⎞ \n", "(x + 1)⋅⎝- tanh (x + 3) + 1⎠⋅sin(x + 2) + (x + 1)⋅cos(x + 2)⋅tanh(x + 3) + sin\n", "\n", " \n", "(x + 2)⋅tanh(x + 3)" ] }, "execution_count": 23, "metadata": {}, "output_type": "execute_result" } ], "source": [ "diff(exp2)" ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [ { "data": { "text/latex": [ "$$\\frac{1}{a + 3} + \\frac{1}{a + 2}$$" ], "text/plain": [ " 1 1 \n", "───── + ─────\n", "a + 3 a + 2" ] }, "execution_count": 24, "metadata": {}, "output_type": "execute_result" } ], "source": [ "exp4" ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [ { "data": { "text/latex": [ "$$\\log{\\left (a + 1 \\right )} - \\log{\\left (a + 2 \\right )}$$" ], "text/plain": [ "log(a + 1) - log(a + 2)" ] }, "execution_count": 25, "metadata": {}, "output_type": "execute_result" } ], "source": [ "integrate(exp3, a)" ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [ { "data": { "text/latex": [ "$$\\sqrt{\\pi}$$" ], "text/plain": [ "√π" ] }, "execution_count": 26, "metadata": {}, "output_type": "execute_result" } ], "source": [ "integrate(exp(-x**2), (x, -oo, oo))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 4.2 Sum and Products" ] }, { "cell_type": "code", "execution_count": 27, "metadata": {}, "outputs": [ { "data": { "text/latex": [ "$$\\frac{1}{n^{2}}$$" ], "text/plain": [ "1 \n", "──\n", " 2\n", "n " ] }, "execution_count": 27, "metadata": {}, "output_type": "execute_result" } ], "source": [ "n = Symbol(\"n\")\n", "exp5 = 1/n**2\n", "exp5" ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [ { "data": { "text/latex": [ "$$\\sum_{n=1}^{\\infty} \\frac{1}{n^{2}}$$" ], "text/plain": [ " ∞ \n", " ____ \n", " ╲ \n", " ╲ 1 \n", " ╲ ──\n", " ╱ 2\n", " ╱ n \n", " ╱ \n", " ‾‾‾‾ \n", "n = 1 " ] }, "execution_count": 28, "metadata": {}, "output_type": "execute_result" } ], "source": [ "Sum(exp5, (n, 1, oo))" ] }, { "cell_type": "code", "execution_count": 29, "metadata": {}, "outputs": [ { "data": { "text/latex": [ "$$1.64493406684823$$" ], "text/plain": [ "1.64493406684823" ] }, "execution_count": 29, "metadata": {}, "output_type": "execute_result" } ], "source": [ "Sum(exp5, (n, 1, oo)).evalf()" ] }, { "cell_type": "code", "execution_count": 30, "metadata": {}, "outputs": [ { "data": { "text/latex": [ "$$\\prod_{n=1}^{\\infty} \\frac{1}{n^{2}}$$" ], "text/plain": [ " ∞ \n", "┬────────┬ \n", "│ │ 1 \n", "│ │ ──\n", "│ │ 2\n", "│ │ n \n", "│ │ \n", " n = 1 " ] }, "execution_count": 30, "metadata": {}, "output_type": "execute_result" } ], "source": [ "Product(exp5, (n, 1, oo))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 4.3 Limits" ] }, { "cell_type": "code", "execution_count": 31, "metadata": {}, "outputs": [ { "data": { "text/latex": [ "$$\\infty$$" ], "text/plain": [ "∞" ] }, "execution_count": 31, "metadata": {}, "output_type": "execute_result" } ], "source": [ "limit(1/x, x, 0, dir=\"+\")" ] }, { "cell_type": "code", "execution_count": 32, "metadata": {}, "outputs": [ { "data": { "text/latex": [ "$$-\\infty$$" ], "text/plain": [ "-∞" ] }, "execution_count": 32, "metadata": {}, "output_type": "execute_result" } ], "source": [ "limit(1/x, x, 0, dir=\"-\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 4.4 Series" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "By default it expands the expression around $x=0$, but we can expand around any value of $x$ by explicitly include a value in the function call. It's possible to specify to which order the series expansion should be carried out:" ] }, { "cell_type": "code", "execution_count": 33, "metadata": {}, "outputs": [ { "data": { "text/latex": [ "$$1 + x + \\frac{x^{2}}{2} + \\frac{x^{3}}{6} + \\frac{x^{4}}{24} + \\frac{x^{5}}{120} + \\mathcal{O}\\left(x^{6}\\right)$$" ], "text/plain": [ " 2 3 4 5 \n", " x x x x ⎛ 6⎞\n", "1 + x + ── + ── + ── + ─── + O⎝x ⎠\n", " 2 6 24 120 " ] }, "execution_count": 33, "metadata": {}, "output_type": "execute_result" } ], "source": [ "exp6 = exp(x)\n", "series(exp6, x)" ] }, { "cell_type": "code", "execution_count": 34, "metadata": {}, "outputs": [ { "data": { "text/latex": [ "$$e + e \\left(x - 1\\right) + \\frac{e}{2} \\left(x - 1\\right)^{2} + \\frac{e}{6} \\left(x - 1\\right)^{3} + \\frac{e}{24} \\left(x - 1\\right)^{4} + \\frac{e}{120} \\left(x - 1\\right)^{5} + \\frac{e}{720} \\left(x - 1\\right)^{6} + \\frac{e}{5040} \\left(x - 1\\right)^{7} + \\frac{e}{40320} \\left(x - 1\\right)^{8} + \\frac{e}{362880} \\left(x - 1\\right)^{9} + \\mathcal{O}\\left(\\left(x - 1\\right)^{10}; x\\rightarrow 1\\right)$$" ], "text/plain": [ " 2 3 4 5 6\n", " ℯ⋅(x - 1) ℯ⋅(x - 1) ℯ⋅(x - 1) ℯ⋅(x - 1) ℯ⋅(x - 1) \n", "ℯ + ℯ⋅(x - 1) + ────────── + ────────── + ────────── + ────────── + ──────────\n", " 2 6 24 120 720 \n", "\n", " 7 8 9 \n", " ℯ⋅(x - 1) ℯ⋅(x - 1) ℯ⋅(x - 1) ⎛ 10 ⎞\n", " + ────────── + ────────── + ────────── + O⎝(x - 1) ; x → 1⎠\n", " 5040 40320 362880 " ] }, "execution_count": 34, "metadata": {}, "output_type": "execute_result" } ], "source": [ "series(exp(x), x, 1, 10)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 5 Linear algebra" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 5.1 Matrices" ] }, { "cell_type": "code", "execution_count": 35, "metadata": { "scrolled": false }, "outputs": [ { "data": { "text/latex": [ "$$\\left[\\begin{matrix}m_{11} & m_{12}\\\\m_{21} & m_{22}\\end{matrix}\\right]$$" ], "text/plain": [ "⎡m₁₁ m₁₂⎤\n", "⎢ ⎥\n", "⎣m₂₁ m₂₂⎦" ] }, "execution_count": 35, "metadata": {}, "output_type": "execute_result" } ], "source": [ "m11, m12, m21, m22 = symbols(\"m11, m12, m21, m22\")\n", "b1, b2 = symbols(\"b1, b2\")\n", "A = Matrix([[m11, m12],[m21, m22]])\n", "A" ] }, { "cell_type": "code", "execution_count": 36, "metadata": {}, "outputs": [ { "data": { "text/latex": [ "$$\\left[\\begin{matrix}b_{1}\\\\b_{2}\\end{matrix}\\right]$$" ], "text/plain": [ "⎡b₁⎤\n", "⎢ ⎥\n", "⎣b₂⎦" ] }, "execution_count": 36, "metadata": {}, "output_type": "execute_result" } ], "source": [ "b = Matrix([[b1], [b2]])\n", "b" ] }, { "cell_type": "code", "execution_count": 37, "metadata": {}, "outputs": [ { "data": { "text/latex": [ "$$\\left[\\begin{matrix}b_{1} m_{11} + b_{2} m_{12}\\\\b_{1} m_{21} + b_{2} m_{22}\\end{matrix}\\right]$$" ], "text/plain": [ "⎡b₁⋅m₁₁ + b₂⋅m₁₂⎤\n", "⎢ ⎥\n", "⎣b₁⋅m₂₁ + b₂⋅m₂₂⎦" ] }, "execution_count": 37, "metadata": {}, "output_type": "execute_result" } ], "source": [ "A * b" ] }, { "cell_type": "code", "execution_count": 38, "metadata": {}, "outputs": [ { "data": { "text/latex": [ "$$m_{11} m_{22} - m_{12} m_{21}$$" ], "text/plain": [ "m₁₁⋅m₂₂ - m₁₂⋅m₂₁" ] }, "execution_count": 38, "metadata": {}, "output_type": "execute_result" } ], "source": [ "A.det()" ] }, { "cell_type": "code", "execution_count": 39, "metadata": {}, "outputs": [ { "data": { "text/latex": [ "$$\\left[\\begin{matrix}\\frac{m_{22}}{m_{11} m_{22} - m_{12} m_{21}} & - \\frac{m_{12}}{m_{11} m_{22} - m_{12} m_{21}}\\\\- \\frac{m_{21}}{m_{11} m_{22} - m_{12} m_{21}} & \\frac{m_{11}}{m_{11} m_{22} - m_{12} m_{21}}\\end{matrix}\\right]$$" ], "text/plain": [ "⎡ m₂₂ -m₁₂ ⎤\n", "⎢───────────────── ─────────────────⎥\n", "⎢m₁₁⋅m₂₂ - m₁₂⋅m₂₁ m₁₁⋅m₂₂ - m₁₂⋅m₂₁⎥\n", "⎢ ⎥\n", "⎢ -m₂₁ m₁₁ ⎥\n", "⎢───────────────── ─────────────────⎥\n", "⎣m₁₁⋅m₂₂ - m₁₂⋅m₂₁ m₁₁⋅m₂₂ - m₁₂⋅m₂₁⎦" ] }, "execution_count": 39, "metadata": {}, "output_type": "execute_result" } ], "source": [ "A.inv()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 6 Solving Equations" ] }, { "cell_type": "code", "execution_count": 40, "metadata": {}, "outputs": [ { "data": { "text/latex": [ "$$- a + x^{4} - x^{2}$$" ], "text/plain": [ " 4 2\n", "-a + x - x " ] }, "execution_count": 40, "metadata": {}, "output_type": "execute_result" } ], "source": [ "exp7 = x**4 - x**2 - a\n", "exp7" ] }, { "cell_type": "code", "execution_count": 41, "metadata": {}, "outputs": [ { "data": { "text/latex": [ "$$\\left [ - \\sqrt{- \\frac{1}{2} \\sqrt{4 a + 1} + \\frac{1}{2}}, \\quad \\sqrt{- \\frac{1}{2} \\sqrt{4 a + 1} + \\frac{1}{2}}, \\quad - \\sqrt{\\frac{1}{2} \\sqrt{4 a + 1} + \\frac{1}{2}}, \\quad \\sqrt{\\frac{1}{2} \\sqrt{4 a + 1} + \\frac{1}{2}}\\right ]$$" ], "text/plain": [ "⎡ ___________________ ___________________ _________________ \n", "⎢ ╱ _________ ╱ _________ ╱ _________ \n", "⎢ ╱ ╲╱ 4⋅a + 1 1 ╱ ╲╱ 4⋅a + 1 1 ╱ ╲╱ 4⋅a + 1 1 \n", "⎢- ╱ - ─────────── + ─ , ╱ - ─────────── + ─ , - ╱ ─────────── + ─ ,\n", "⎣ ╲╱ 2 2 ╲╱ 2 2 ╲╱ 2 2 \n", "\n", " _________________⎤\n", " ╱ _________ ⎥\n", " ╱ ╲╱ 4⋅a + 1 1 ⎥\n", " ╱ ─────────── + ─ ⎥\n", " ╲╱ 2 2 ⎦" ] }, "execution_count": 41, "metadata": {}, "output_type": "execute_result" } ], "source": [ "solve(exp7,x)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---\n", "\n", "Visit [www.add-for.com]() for more tutorials and updates.\n", "\n", "This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License." ] } ], "metadata": { "kernelspec": { "display_name": "Python [conda env:addfor_tutorials]", "language": "python", "name": "conda-env-addfor_tutorials-py" }, "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.6.4" } }, "nbformat": 4, "nbformat_minor": 1 }