{ "metadata": { "name": "", "signature": "sha256:5f38c57d9570e4b6f6edf98c38a7bff81cd16365baa11fd40265f1504bfc008c" }, "nbformat": 3, "nbformat_minor": 0, "worksheets": [ { "cells": [ { "cell_type": "heading", "level": 1, "metadata": {}, "source": [ "Factoring Polynomials with SymPy" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here is an example that uses [SymPy](http://sympy.org/en/index.html) to factor polynomials." ] }, { "cell_type": "code", "collapsed": false, "input": [ "from IPython.html.widgets import interact\n", "from IPython.display import display" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 1 }, { "cell_type": "code", "collapsed": false, "input": [ "from sympy import Symbol, Eq, factor, init_printing\n", "init_printing(use_latex='mathjax')" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 2 }, { "cell_type": "code", "collapsed": false, "input": [ "x = Symbol('x')" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 3 }, { "cell_type": "code", "collapsed": false, "input": [ "def factorit(n):\n", " display(Eq(x**n-1, factor(x**n-1)))" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 4 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Notice how the output of the factorit function is properly formatted LaTeX." ] }, { "cell_type": "code", "collapsed": false, "input": [ "factorit(12)" ], "language": "python", "metadata": {}, "outputs": [ { "latex": [ "$$x^{12} - 1 = \\left(x - 1\\right) \\left(x + 1\\right) \\left(x^{2} + 1\\right) \\left(x^{2} - x + 1\\right) \\left(x^{2} + x + 1\\right) \\left(x^{4} - x^{2} + 1\\right)$$" ], "metadata": {}, "output_type": "display_data", "text": [ " 12 \u239b 2 \u239e \u239b 2 \u239e \u239b 2 \u239e \u239b 4 2 \u239e\n", "x - 1 = (x - 1)\u22c5(x + 1)\u22c5\u239dx + 1\u23a0\u22c5\u239dx - x + 1\u23a0\u22c5\u239dx + x + 1\u23a0\u22c5\u239dx - x + 1\u23a0" ] } ], "prompt_number": 5 }, { "cell_type": "code", "collapsed": false, "input": [ "interact(factorit, n=(2,40));" ], "language": "python", "metadata": {}, "outputs": [ { "latex": [ "$$x^{21} - 1 = \\left(x - 1\\right) \\left(x^{2} + x + 1\\right) \\left(x^{6} + x^{5} + x^{4} + x^{3} + x^{2} + x + 1\\right) \\left(x^{12} - x^{11} + x^{9} - x^{8} + x^{6} - x^{4} + x^{3} - x + 1\\right)$$" ], "metadata": {}, "output_type": "display_data", "text": [ " 21 \u239b 2 \u239e \u239b 6 5 4 3 2 \u239e \u239b 12 11 \n", "x - 1 = (x - 1)\u22c5\u239dx + x + 1\u23a0\u22c5\u239dx + x + x + x + x + x + 1\u23a0\u22c5\u239dx - x + x\n", "\n", "9 8 6 4 3 \u239e\n", " - x + x - x + x - x + 1\u23a0" ] } ], "prompt_number": 6 }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] } ], "metadata": {} } ] }