Let's create the strongest calculator environment with Sympy + Jupyter.
Sympy is an algebraic math library written in Python, think of it like Mathematica or Maxima. It's easier for programmers to write formulas in Python, the page below is a great introduction to Sympy, and if you don't know Sympy, read on.
3.2. Sympy: Algebraic Calculations in Python
You don't have to do anything special, but type'magic' to display the formulas and graphs in the first cell of Jupyter.
from sympy import *
init_printing()
Next, let's type a formula.
x = Symbol('x')
y = Symbol('y')
Rational(3 ,2)*pi + exp(I*x) / (x**2 + y)
If the formula comes out, it is successful.
According to the information from @ void99_, there is something called ʻinit_session that is more sophisticated than ʻinit_printing
.
from sympy import *
init_session()
Frequently used variables and functions are predefined, which is convenient.
IPython console for SymPy 1.0 (Python 3.5.2-64-bit) (ground types: python)
These commands were executed:
>>> from __future__ import division
>>> from sympy import *
>>> x, y, z, t = symbols('x y z t')
>>> k, m, n = symbols('k m n', integer=True)
>>> f, g, h = symbols('f g h', cls=Function)
>>> init_printing()
Documentation can be found at http://docs.sympy.org/1.0/
Formula symbols can be set with `Symbol'.
x = Symbol('x')
y = Symbol('y')
Multiple symbols can be set at once by using symbols
.
x, y = symbols("x y")
It can also be set using the sympy.abc
module.
from sympy.abc import x, y
The most convenient function when treating it as a calculator is to simplify the formula. If you knead the formula, you can make a very long formula, but if you use Sympy, it is one shot.
For example, suppose you have the following formula: This formula is probably a Bezier curve formula or something that I knead.
(A-B)*C + B**2 + (-B-A)*C + B**2
Written in Sympy, it looks like this:
from sympy.abc import A, B, C
f = (A-B)*C + B**2 + (-B-A)*C + B**2
2 B^{2} + C \left(- A - B\right) + C \left(A - B\right)
Substituting an expression into Sympy will sort the terms for clarity.
If you want to further simplify the formula, use simpfly
.
simplify(f)
2 B \left(B - C\right)
ʻAhas disappeared and it has become extremely simple. You can also use
ratsimp`, which is often used in Maxima.
ratsimp(f)
2 B^{2} - 2 B C
There are many types of formula simplifications, see below for details.
http://docs.sympy.org/dev/modules/simplify/simplify.html
from sympy.abc import A, B, C, D
(A-B)*D + C**2 + (-B-A)*C+B**2
B^{2} + C^{2} + C \left(- A - B\right) + D \left(A - B\right)
If you want to solve ʻA in the above formula, use
solve`.
solve((A-B)*D + C**2 + (-B-A)*C+B**2, A)
\left [ \frac{1}{C - D} \left(B^{2} - B C - B D + C^{2}\right)\right ]
You can assign a value to a variable in an expression with subs
.
f = (A-B)*D + C**2 + (-B-A)*C+B**2
# A,B,Assign a value to C
f.subs([(A, 10), (B, 20), (C, 30)])
- 10 D + 400
The argument of subs
can also be passed a dictionary.
f.subs({A: 10, B: 20, C: 30})
- 10 D + 400
If there is only one variable you want to assign, you can specify a variable in the first argument and a value in the second argument.
f.subs(A, 10)
B^{2} + C^{2} + C \left(- B - 10\right) + D \left(- B + 10\right)
Use diff
for differentiation / partial differentiation.
diff(x**2 + 3*x + 100)
2 x + 3
For partial differential, specify the second argument.
diff(3*x**2 + 3*x*y + y**2, x)
6 x + 3 y
Factorize uses factor
.
factor(x**2-x-6)
\left(x - 3\right) \left(x + 2\right)
Use factor int
for prime factorization.
factorint(3417)
>>> {3:1,17:1,67:1}
The dictionary is returned, which means 3 ^ 1 * 17 ^ 1 * 67 ^ 1 = 3417
.
Use the Matrix
class.
Matrix([[1, 0], [0, 1]])
\left[\begin{matrix}1 & 0\\0 & 1\end{matrix}\right]
There is a vector, but it is difficult to use, so treat it as a one-column matrix.
θ = Symbol("θ")
P = Matrix([2*cos(θ), 2*sin(θ)])
\left[\begin{matrix}2 \cos{\left (θ \right )}\\2 \sin{\left (θ \right )}\end{matrix}\right]
To perform vector operations, use the transpose
function to transpose.
transpose(P) * P
\left[\begin{matrix}4 \sin^{2}{\left (θ \right )} + 4 \cos^{2}{\left (θ \right )}\end{matrix}\right]
With Jupyter and Sympy, you can easily copy the output formulas to Qiita. Right-click on the formula and select Show Math As → Tex Commands.
A pop-up like this will appear, so copy and paste the formula.
This Latex is convenient because it can be pasted directly on Qiita.
ASCII art with pprint
? You can also output formulas with.
pprint(Integral(sqrt(1/x), x), use_unicode=True)
"""
⌠
⎮ ___
⎮ ╱ 1
⎮ ╱ ─ dx
⎮ ╲╱ x
⌡
"""
It's convenient when pasting formulas into source code.
You can draw a graph with sympy.plotting.plot
.
It is convenient because you can pass the formula of Sympy
as an argument as it is.
from sympy.plotting import plot
y = -(x+2)*(x+1)*(x-1)
#x is-Draw a graph from 4 to 4
plot(y, (x, -4, 4))
Jupyter + Sympy is very convenient, but you have to type magic
in the first cell every time.
This is surprisingly troublesome, isn't it?
In my article, there is Generate Jupyter notebook ".ipynb" in Python. Using this, let's write a script that will generate ipynb with various inputs from the beginning.
PyCharm is a Python integrated development environment (IDE), which has very powerful complementary features and is the strongest Python development environment. Actually, PyCharm can be linked with Jupyter, and Jupyter's expressive power + PyCharm's powerful complementary function is quite comfortable.
However, when dealing with mathematical formulas, PyCharm's Jupyter output is poor, so it is better to use the browser version of Jupyter. So I don't use PyCharm's Jupyter, instead I use ʻExtranal Tools`.
Create the following script somewhere that is easy to refer to.
#!/usr/bin/env python3
# coding:utf-8
import sys
import os
import nbformat
output_dir = sys.argv[1]
output_file = input("input ipynb name:")
nb = nbformat.v4.new_notebook()
title = "#title"
code = """
%matplotlib inline
from sympy import *
init_session()
"""
nb["cells"] = [
nbformat.v4.new_markdown_cell(title),
nbformat.v4.new_code_cell(code)
]
if not output_file.endswith(".ipynb"):
output_file += ".ipynb"
with open(os.path.join(output_dir, output_file), "w") as f:
nbformat.write(nb, f)
print("ok.")
Open PyCharm's File (F) menu and select Settings ...
Select "Tools"-> "External Tools" in the settings dialog and press the "+" button.
The setting dialog will appear, so add the following items.
item | input |
---|---|
Name | Please enter a suitable name |
Description | Please enter an appropriate explanation |
Program | Python path where Jupyter is installed |
Parameters | The script path from earlier$FileDir$ |
Select "External Toos"-> "Registered Tool Name" from the right-click menu of PyCharm.
When you enter the file name in the console, various pre-filled .ipynb files will be generated from the beginning.
If you have a more convenient way to use it, please post it.
The output of .ipynb was longer than Sympy, but Sympy is very useful.
It is very useful for game programmers and those who use mathematical formulas. This library is for those who are not good at math.
Recommended Posts