将计算结果插入LaTeX文档
为了我的实验室实验,我写了一些程序来处理我的测量数据。这些程序目前在终端上打印出一份简单的数据总结,像这样:
U = 2.0 ± 0.1 V
I = 6.0 ± 0.2 A
因为我都是手动写的,所以我就用这些数据在文本中写成了叙述。
现在,我们可以在电脑上制作报告了。我用LaTeX写报告,想要把程序的结果自动插入到文本中。这样,我就可以重新运行程序,而不需要手动复制粘贴结果到文本里。由于我的测量和结果差异很大,我考虑使用模板语言。因为我已经在用Python,所以我想到了Jinja,像这样:
article.tex
We measured the voltage $U = \unit{<< u_val >> \pm << u_err >>}{\volt}$ and the
current $I = \unit{<< i_val >> \pm << i_err >>}{\ampere}$. Then we computed the
resistance $R = \unit{<< r_val >> \pm << r_err >>}{\ohm}$.
All our measurements:
\begin{table}[h]
\begin{tabular}{rrr}
$U/\volt$ & $I/\ampere$ \\
\hline
%< for u, i in data: ->%
$<< u >>$ & $<< i >>$ \\
%< endfor ->%
\end{tabular}
\end{table}
program.py
# Setting up Jinja
env = jinja2.Environment(
"%<", ">%",
"<<", ">>",
"[§", "§]",
loader=jinja2.FileSystemLoader(".")
)
template = env.get_template("article.tex")
# Measurements.
u_val = 6.2
u_err = 0.1
i_val = 2.0
i_err = 0.1
data = [
(3, 4),
(1, 4.0),
(5, 1),
]
# Calculations
r_val = u_val / i_val
r_err = math.sqrt(
(1/i_val * u_err)**2
+ (u_val/i_val**2 * i_err)**2
)
# Rendering LaTeX document with values.
with open("out.tex", "w") as f:
f.write(template.render(**locals()))
out.tex
We measured the voltage $U = \unit{6.2 \pm 0.1}{\volt}$ and the current $I =
\unit{2.0 \pm 0.1}{\ampere}$. Then we computed the resistance $R = \unit{3.1
\pm 0.162864974749}{\ohm}$.
All our measurements:
\begin{table}[h]
\begin{tabular}{rrr}
$U/\volt$ & $I/\ampere$ \\
\hline
$3$ & $4$ \\
$1$ & $4.0$ \\
$5$ & $1$ \\
\end{tabular}
\end{table}
结果看起来不错,只是有一个数字需要四舍五入。
我的问题是:这样做是否合适,或者有没有更好的方法把数字放到文档里?