Reputation: 8719
For my lab experiments, I write programs that do calculations with my measurements. Currently, those programs print out a plain summary of all the data in the terminal, like so:
U = 2.0 ± 0.1 V
I = 6.0 ± 0.2 A
Since I had to write them by hand, I would just use those to write prose with the values in the text.
From now on, we are allowed create our reports on the computer. I write my report in LaTeX and would like to have the results from the program automatically inserted into the text. That way, I can re-run the program without having to copy-paste the results into the text. Since the measurements and results are very heterogeneous, I thought about using a template language. Since I already use Python, I thought about Jinja like so:
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}
The result looks pretty good, except that the one number would need rounding.
My question is: Would that be a good way to do this, or are there better ways to get the numbers into the document?
Upvotes: 3
Views: 2144
Reputation: 376
There are actually LaTeX packages for this sort of thing. I'm the author of the pythontex package. See the pythontex_gallery file for a quick example of what's possible.
Upvotes: 2
Reputation: 274
Replacing
<< r_err >>
with
<< '%.2f' % r_err|float >>
should give you an output with two decimals.
Or, you could convert your values to strings before rendering.
r_err = "%.2f" % r_err
Upvotes: 5