Pythonコードで計算しながらTex形式で数式を表示する¶
pythonでいろいろ計算する時,その数式をちゃんと表示させたい → renderというセルマジックを使う
参考にしたサイト(https://blog.masahiko.info/entry/2020/09/03/162704, https://medium.com/@zumaia/python-calculations-in-jupyter-like-you-wrote-them-by-hand-b8e7728c0a40)
必要なライブラリはhandcalcs
とforallpeople
らしいが後者はいらなかったのかも
これらをpip3でインストール
$ pip3 install handcalcs
$ pip3 install forallpeople
その後, jupyter labを再起動して以下のコードを参照
In [1]:
import handcalcs.render
import math
In [2]:
%%render
a = 10
b = 2
c = a*2 + b/3
\[
\begin{aligned}
a &= 10 \;
\\[10pt]
b &= 2 \;
\\[10pt]
c &= a \cdot 2 + \frac{ b }{ 3 } = 10 \cdot 2 + \frac{ 2 }{ 3 } &= 20.667
\end{aligned}
\]
以下のような複雑な式でもいけるっぽい
注意として,pi
とかsqrt
はmath
から指定してインポートしないとtex形式で表示してくれない
In [3]:
from math import pi, sqrt
from scipy import constants as phys
e = phys.e # c
h = phys.h/e # eV
c = phys.c # m/s
m_n = phys.m_n*c**2/e # eV/c/c
In [4]:
%%render
h # Plank const
e # elementary charge
c # right
L = 1.00 # m
lam = 1e-9 #m
delta_phi = (0.03 / 58)
delta_U = delta_phi/(2.*pi)*h**2/((m_n/c**2)*lam*L)
\[
\begin{aligned}
h &= 0.000 \; \;\textrm{(Plank const)}
\\[10pt]
e &= 0.000 \; \;\textrm{(elementary charge)}
\\[10pt]
c &= 299792458.000 \; \;\textrm{(right)}
\\[10pt]
L &= 1.000 \; \;\textrm{(m)}
\\[10pt]
\mathrm{lam} &= 0.000 \; \;\textrm{(m)}
\\[10pt]
\delta_{\phi} &= 0.001 \;
\\[10pt]
\delta_{U} &= \frac{ \delta_{\phi} }{ 2. \cdot \pi } \cdot \frac{ \left( h \right) ^{ 2 } }{ \left( \frac{ m_{n} }{ \left( c \right) ^{ 2 } } \right) \cdot \mathrm{lam} \cdot L } \\&= \frac{ 0.001 }{ 2. \cdot 3.142 } \cdot \frac{ \left( 0.000 \right) ^{ 2 } }{ \left( \frac{ 939565420.520 }{ \left( 299792458.000 \right) ^{ 2 } } \right) \cdot 0.000 \cdot 1.000 } \\&= 0.000 \\[10pt]
\end{aligned}
\]
In [5]:
import sympy
sympy.init_printing()
sympy.var('x')
eq = sympy.Eq(x**2, 2*x + 1)
eq
# 解を取得
s = sympy.solve(eq, x)
print("方程式の左辺 {}".format(eq.lhs))
print("方程式の右辺 {}".format(eq.rhs))
print("方程式の解 :", s)
方程式の左辺 x**2 方程式の右辺 2*x + 1 方程式の解 : [1 - sqrt(2), 1 + sqrt(2)]
In [6]:
#final update
!date '+%b %d %Y (%a)'
9 28 2023 (木)
In [ ]:
In [ ]: