對於我的實驗室實驗,我編寫的程序可以用我的測量值進行計算。目前,這些程序打印出所有數據的平原總結在終端上,像這樣:將計算結果插入LaTeX文檔
U = 2.0 ± 0.1 V
I = 6.0 ± 0.2 A
因爲我不得不用手工寫他們,我只想用那些寫散文在文本中的值。
從現在起,我們可以在電腦上創建我們的報告。我在LaTeX中撰寫報告,並希望將程序的結果自動插入到文本中。這樣,我可以重新運行該程序,而無需將結果複製粘貼到文本中。由於測量和結果非常不同,我想到了使用模板語言。既然我已經使用Python,我想到了神社,像這樣:
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}
結果看起來不錯,除了一個數字需要四捨五入。
我的問題是:這是否是一個很好的方法來做到這一點,或者有更好的方法來獲得數字的文件?
爲什麼你應用'| float'?它是否會根據區域設置更改小數點分隔符? – 2013-02-14 16:31:15
'| float'只是添加浮點過濾器,意味着在渲染之前將值傳遞給名爲float的(python)函數,確保它在將其格式化爲字符串之前實際上是一個浮點數。如果您願意,您可以創建自己的自定義過濾器。 – frogge 2013-02-14 18:12:50
@queueoverflow它解決了你的問題嗎? – frogge 2013-03-04 14:52:34