Discussion:
evaluation of math expressions in latex (newbie question)
(too old to reply)
New Teacher
2008-05-19 10:18:21 UTC
Permalink
Hello,

I was a LaTex user in the early 90's when I was in grad school, but
since then I've been stuck in a MS Word world like most everyone
else. Recently, however, I've stumbled on a PC version of LaTex
(MiKTex 2.7) and I'd like to be able to use it productively for my
job.

I'm currently a high school physics teacher and this is the kind of
thing I'd like to be able to do, if possible: I need to re-create
the same physics problem with multiple sets of numerical data. For
example, I'd like to be able to set variables for, say mass and
acceleration, and possibly have them evaluated automatically and the
results inserted into the text.

In other words, to be able to go from:

m = (2)
a = (2)

A mass of (m) kg is accelerating at (a) m/s^2. What net force is
acting upon the mass?

F= ma = (2 kg)(2 m/s^2) = 4N

to something that appears like this:

A mass of 2 kg is accelerating at 2 m/s^2. What net force is acting
upon the mass?

F= ma = (2 kg)(2 m/s^2) = 4N % Appears only in instructor edition %


Is it possible to do something like this?

Thank you very much

John
Nicola Talbot
2008-05-19 10:35:56 UTC
Permalink
Post by New Teacher
Hello,
I was a LaTex user in the early 90's when I was in grad school, but
since then I've been stuck in a MS Word world like most everyone
else. Recently, however, I've stumbled on a PC version of LaTex
(MiKTex 2.7) and I'd like to be able to use it productively for my
job.
I'm currently a high school physics teacher and this is the kind of
thing I'd like to be able to do, if possible: I need to re-create
the same physics problem with multiple sets of numerical data. For
example, I'd like to be able to set variables for, say mass and
acceleration, and possibly have them evaluated automatically and the
results inserted into the text.
m = (2)
a = (2)
A mass of (m) kg is accelerating at (a) m/s^2. What net force is
acting upon the mass?
F= ma = (2 kg)(2 m/s^2) = 4N
A mass of 2 kg is accelerating at 2 m/s^2. What net force is acting
upon the mass?
F= ma = (2 kg)(2 m/s^2) = 4N % Appears only in instructor edition %
Is it possible to do something like this?
Thank you very much
John
For the arithmetic:

\documentclass{article}

\usepackage{fp}

\begin{document}
\newcommand*{\mass}{2}
\newcommand*{\acceleration}{2}

A mass of \mass kg is accelerating at
$\acceleration \mathrm{m}/\mathrm{s}^2$.
What net force is acting upon the mass?

\FPmul{\force}{\mass}{\acceleration}% force = mass x acceleration
\FPclip{\force}{\force}% remove trailing 0s
\begin{displaymath}
F= ma = (\mass \mathrm{kg})(\acceleration \mathrm{m}/\mathrm{s}^2)
= \force \mathrm{N}
\end{displaymath}
\end{document}

There are several packages dealing with typesetting units, such as
siunits. The probsoln package provides a way of defining problems and
their solutions in a database and either displaying both problem and
solution, or hiding the solution.

Regards
Nicola Talbot
Joseph Wright
2008-05-19 11:48:45 UTC
Permalink
Post by Nicola Talbot
There are several packages dealing with typesetting units,
Although it is currently in beta, the siunitx package is targeted as a
replacement for siunits, etc. Modifying Nicola's example:

\documentclass{article}

\usepackage{fp,siunitx}

\begin{document}
\newcommand*{\mass}{2}
\newcommand*{\acceleration}{2}
\newunit{\mpss}{\metre\per\second\squared}

A mass of \SI{\mass}{\kg} is accelerating at
\SI{\acceleration}{\mpss}. What net force is acting upon the
mass?

\FPmul{\force}{\mass}{\acceleration}% force = mass x acceleration
\FPclip{\force}{\force}% remove trailing 0s
\begin{displaymath}
F = ma =
(\SI{\mass}{\kg})
(\SI{\acceleration} {\mpss}) =
\SI{\force}{\newton}
\end{displaymath}
\end{document}

Joseph Wright
Scott Pakin
2008-05-19 17:25:34 UTC
Permalink
Post by New Teacher
I'm currently a high school physics teacher and this is the kind of
thing I'd like to be able to do, if possible: I need to re-create
the same physics problem with multiple sets of numerical data. For
example, I'd like to be able to set variables for, say mass and
acceleration, and possibly have them evaluated automatically and the
results inserted into the text.
In addition to what Nicola and Joseph have written you may also want to
take a look at PerlTeX, which lets you execute Perl code from within a
LaTeX document. If you're doing calculations that require more than
addition, subtraction, multiplication, and division of fixed-point numbers
you may find it convenient to let Perl do the number-crunching while LaTeX
does only the typesetting.

-- Scott
Christian Stapfer
2008-05-19 19:13:10 UTC
Permalink
Post by Scott Pakin
Post by New Teacher
I'm currently a high school physics teacher and this is the kind of
thing I'd like to be able to do, if possible: I need to re-create
the same physics problem with multiple sets of numerical data. For
example, I'd like to be able to set variables for, say mass and
acceleration, and possibly have them evaluated automatically and the
results inserted into the text.
In addition to what Nicola and Joseph have written you may also want to
take a look at PerlTeX, which lets you execute Perl code from within a
LaTeX document.
.. or you can simply have a program written in the language of your[!]
choice generate the entire LaTeX document.
Scott Pakin
2008-05-19 21:31:54 UTC
Permalink
Post by Christian Stapfer
Post by Scott Pakin
In addition to what Nicola and Joseph have written you may also want to
take a look at PerlTeX, which lets you execute Perl code from within a
LaTeX document.
.. or you can simply have a program written in the language of your[!]
choice generate the entire LaTeX document.
For the OP's needs, that's probably true, and it's good that you brought
that up. However, PerlTeX does support two-way communication between
LaTeX and Perl, which one doesn't get when generating an entire document.
For example, LaTeX can tell Perl the typeset height of a block of text,
and Perl can generate LaTeX code based on that height.

-- Scott
J.S.Milne
2008-05-19 21:48:25 UTC
Permalink
Post by New Teacher
m = (2)
a = (2)
A mass of (m) kg is accelerating at (a) m/s^2. What net force is
acting upon the mass?
F= ma = (2 kg)(2 m/s^2) = 4N
A mass of 2 kg is accelerating at 2 m/s^2. What net force is acting
upon the mass?
F= ma = (2 kg)(2 m/s^2) = 4N % Appears only in instructor edition %
Is it possible to do something like this?
Thank you very much
John
Scientific Notebook and Scientific Workplace are TeX front ends with
MuPad built in, so you can solve differential equations, multiply
matrices, and so on with a couple of clicks and have the result show
up in your TeX file. I found this extremely useful when I was teaching
undergraduate courses. Unfortunately, they are expensive. You can get
a trial version from
http://www.mackichan.com/
David C. Ullrich
2008-05-20 09:07:29 UTC
Permalink
On Mon, 19 May 2008 03:18:21 -0700 (PDT), New Teacher
Post by New Teacher
Hello,
I was a LaTex user in the early 90's when I was in grad school, but
since then I've been stuck in a MS Word world like most everyone
else. Recently, however, I've stumbled on a PC version of LaTex
(MiKTex 2.7) and I'd like to be able to use it productively for my
job.
I'm currently a high school physics teacher and this is the kind of
thing I'd like to be able to do, if possible: I need to re-create
the same physics problem with multiple sets of numerical data. For
example, I'd like to be able to set variables for, say mass and
acceleration, and possibly have them evaluated automatically and the
results inserted into the text.
m = (2)
a = (2)
A mass of (m) kg is accelerating at (a) m/s^2. What net force is
acting upon the mass?
F= ma = (2 kg)(2 m/s^2) = 4N
A mass of 2 kg is accelerating at 2 m/s^2. What net force is acting
upon the mass?
F= ma = (2 kg)(2 m/s^2) = 4N % Appears only in instructor edition %
Is it possible to do something like this?
Various people have suggested various packages that will do something
like this for you, some of which are free and some of which are not.
People have suggested using Perl to just generate the LaTeX.

I don't know how much experience with or enthusiasm for
programming you have - you could also use Python to do
this sort of thing (Python and Perl are both freely available).
Either language would work just fine - a lot of people would
say that Python code is much simpler to understand.
(A lot of Perl fans might disagree.)

What does "easily" mean? It's 3:16 and I'm about to start
writing a little Python code that will do exactly what
you ask for above - let's see how long it takes. In n
minutes I'm going to have something that you could
actually cut&paste from this post and _use_ for a variety
of problems...

OK, it's 3:33. Worked the first time (after fixing three
typos).

Why program it yourself instead of using some existin
package? (i) If the existing package doesn't do exactly
what you want you may have a hard time doing what
you want, while if it's your own code you can make it
do exactly what you want just by writing code to do
whatever (ii) once you know a little bit about a
simple language like Python you'll find you can
use it to solve all sorts of other similar problems
very easily.

Why Python? Because the syntax makes so much sense,
it's easy to learn. I wrote the code below more or less
as fast as I could type, and it worked exactly right
the first time. Ok, when you're starting you won't be
find it quite that easy until you have a little experience
with the language.

Ok, here's the code:


#For this morning pay no attention to the first 20
#or so lines - it's what defines the machine to do the
#job you asked about. You could simply use exactly
#this code as long as you wanted to do exactly
#what you ask for above - when you want to do
#something slightly different you'd modify these
#first 20 lines. For this morning skip down 20
#lines to the part that illustrates how you'd _use_
#this problem-printing machine

class Problem:

def __init__(self, vars, calculation, ST, IT):
"""ST and IT for "StudentTemplate and InstructorTemplate;
some text that defines what LaTeX you want generated for the
problem"""
self.vars = vars
self.calculation = calculation
self.ST = ST
self.IT = IT

def Format(self):
self.calculation(vars)
print 'Student text:'
print
print ST % vars
print
print 'Instrructor Text:'
print
print IT % vars

#Ok, start reading here:

#the code above defines a Problem class. You can
#use the Problem class to define various problems,
#and then print the LaTeX code for the problem.
#You have to set "vars" to a "dict" defining the
#variables, you set "calculate" to a procedure
#that does the calculation to get the answer,
#you set ST and IT to bits of LaTeX containing
#some magic code, you push the button
#by calling the Format() method and the
#LaTeX you want gets "printed". You could easily
#modify this to write the code to a file, whatever...

#For example, with the problem you post, you
#could say this:

ST = """A mass of $%(m)s$ kg is accelerating at $%(a)s$ m/s^2.
What net force is acting upon the mass?"""

IT = ST + """

F = ma = ($%(m)s$ kg)($%(a)s$ m/s^2) = $%(F)s$N"""

#Now ST and IT define how you want the problem
#to appear. Note that ST and IT are just LaTeX
#with magic additions of the form

# %(variable name)s

#wherever that magic bit appears the printout will
#have the value of the variable instead.

#Note you're going to _set_ the values of m and a
#and then the code is going to calculate the value of
#F for you:

#define the calculation that gives the answer:

def calculateFMA(vars):
vars['F'] = vars['m'] * vars['a']
#in other words, F = m*a.

#Now set up the original variables:

vars = {'m': 2, 'a': 2}

#now create the Problem:

problem = Problem(vars, calculateFMA, ST, IT)

#and now print the result:

problem.Format()

#Excellent. Here's the output of that problem.Format()
#command:

"""Student text:

A mass of $2$ kg is accelerating at $2$ m/s^2.
What net force is acting upon the mass?

Instrructor Text:

A mass of $2$ kg is accelerating at $2$ m/s^2.
What net force is acting upon the mass?

F = ma = ($2$ kg)($2$ m/s^2) = $4$N"""

#Exactly what you asked for.

#Now to do the very same problem except
#with m = 3 and a = 4 we simply modify
#vars:

vars['m'] = 3
vars['a'] = 4
problem.Format()

#Here's the output of the second problem.Format():

"""Student text:

A mass of $3$ kg is accelerating at $4$ m/s^2.
What net force is acting upon the mass?

Instrructor Text:

A mass of $3$ kg is accelerating at $4$ m/s^2.
What net force is acting upon the mass?

F = ma = ($3$ kg)($4$ m/s^2) = $12$N"""

#And just as a silly example of another problem,
#here's how you'd do the same problem in another
#universe where F = ma^2. Define a different
#calculation:

def calculateFMA2(vars):
vars['F'] = vars['m'] * (vars['a']**2)

#You also want to revise the formula appearing
#in the instructor's manual:

IT = ST + """

F = ma^2 = ($%(m)s$ kg)($%(a)s$ m/s^2)^2 = $%(F)s$[whatever units]"""

#and then

problem = Problem(vars, calculateFMA2, ST, IT)
problem.Format()

#that last produces this:

"""Student text:

A mass of $3$ kg is accelerating at $4$ m/s^2.
What net force is acting upon the mass?

Instrructor Text:

A mass of $3$ kg is accelerating at $4$ m/s^2.
What net force is acting upon the mass?

F = ma^2 = ($3$ kg)($4$ m/s^2)^2 = $48$[whatever units]"""
Post by New Teacher
Thank you very much
John
David C. Ullrich
Robin Fairbairns
2008-05-20 10:23:49 UTC
Permalink
David C. Ullrich <***@sprynet.com> writes:
[lots of good sensible stuff]
Post by David C. Ullrich
Either language would work just fine - a lot of people would
say that Python code is much simpler to understand.
(A lot of Perl fans might disagree.)
speaking as one who's fluent in perl, i'ld point out that python
doesn't really help if you don't know it.

perl, otoh, is easy to obfuscate. (many of the scripts i maintain
were written by a champion obfuscater...)
--
Robin Fairbairns, Cambridge
David C. Ullrich
2008-05-20 16:03:24 UTC
Permalink
Post by Robin Fairbairns
[lots of good sensible stuff]
Post by David C. Ullrich
Either language would work just fine - a lot of people would
say that Python code is much simpler to understand.
(A lot of Perl fans might disagree.)
speaking as one who's fluent in perl, i'ld point out that python
doesn't really help if you don't know it.
Heh - it does have that drawback.

Many years ago I found Python much easier to learn than
Perl. I didn't have any bias towards Perl at the time,
I'd been learning some Perl, saw PvP flame war on usenet,
looked at Python and found I got much farther much faster.

Probably I should add that that's probably just because
I'm not smart enough.
Post by Robin Fairbairns
perl, otoh, is easy to obfuscate.
Really?
Post by Robin Fairbairns
(many of the scripts i maintain
were written by a champion obfuscater...)
I actually posted some code that solves his problem -
only took a few minutes. What would unobfuscated Perl
to do the same thing look like?

The requirements are you input two "format strings"
defining what the output should look like, you somehow
input a few variables with their values and a function
that calculates the value of some other variables.
Then the routine calls the function to get the
value of the other variables and sticks all the
values into the output.

(I don't know if you can pass a function as a parameter to
another function in Perl - if not some other workaround
is acceptable, but the thing does need to be easily
adapted to various different problems. There were a lot
of comments and example code in what I posted - the actual
solution is this:

class Problem:

def __init__(self, vars, calculation, ST, IT):
"""ST and IT for "StudentTemplate and InstructorTemplate;
some text that defines what LaTeX you want generated for the
problem"""
self.vars = vars
self.calculation = calculation
self.ST = ST
self.IT = IT

def Format(self):
self.calculation(vars)
print 'Student text:'
print
print ST % vars
print
print 'Instrructor Text:'
print
print IT % vars

and that's all. Can you write Perl that does the same thing,
is about the same size, and is equally comprehensible to
someone who knows maybe Basic or Pascal or something but
neither P?)
--
David C. Ullrich
Robin Fairbairns
2008-05-20 17:41:36 UTC
Permalink
Post by David C. Ullrich
I actually posted some code that solves his problem -
only took a few minutes. What would unobfuscated Perl
to do the same thing look like?
dunno. you've solved the problem, so there's no incentive to try (for
me, anyway -- i'm not a perl evangelist, just someone who uses it[*]).

[*] at speeds commensurate with my age, of course.
--
Robin Fairbairns, Cambridge
Michal Jaegermann
2008-05-20 19:30:05 UTC
Permalink
Post by David C. Ullrich
I actually posted some code that solves his problem -
only took a few minutes. What would unobfuscated Perl
to do the same thing look like?
Somewhat more compact and with less format hackery, I would say, which
would make that easier on eyes. At least for me. :-) Otherwise
it would be not really much difference save easier passing variables
to a subroutine in Perl. You could write it in a "procedural" or
"objective" (more Python-like) style. Your choice.
Post by David C. Ullrich
(I don't know if you can pass a function as a parameter to
another function in Perl ....
Yes, you do. For standard examples of use look at 'perldoc -f sort' or
'man File::Find'. In such cases this ability is really important.

Michal
David C. Ullrich
2008-05-21 09:31:35 UTC
Permalink
On Tue, 20 May 2008 19:30:05 +0000 (UTC), Michal Jaegermann
Post by Michal Jaegermann
Post by David C. Ullrich
I actually posted some code that solves his problem -
only took a few minutes. What would unobfuscated Perl
to do the same thing look like?
Somewhat more compact and with less format hackery, I would say, which
would make that easier on eyes. At least for me. :-) Otherwise
it would be not really much difference save easier passing variables
to a subroutine in Perl. You could write it in a "procedural" or
"objective" (more Python-like) style. Your choice.
I wish you'd actually _show_ me what it looks like. One reason
being that it's not at all clear to me that more compact would
be a virtue - it's at least possible that that would make it
easier on the eyes of someone who knows the language
very well but harder to follow for someone who doesn't.
(The Python certainly could be written more compactly.)

When _I_ look at Perl it's typically nice and compact
because it's full of funny little special characters that
don't have any obvious meaning. At least that's the way
it seems to me.

The above is more or less what I had in mind when I asked
the question. Since you mention it, I'm curious what you
mean be talking about easier variable passing.

(Maybe you're referring to that line that says

vars['F'] = vars['m'] * vars['a']

or whatever it was? For this particular problem there's
no reason it would have to be that way - one could just
as well have set things up so that line would read

F = m*a.

That would entail modifying a global variable for the
output, bad, and would either entail using global
variables for input (worse) or require that one write
a routine with a different signature for another problem
where the relevant calculation was something other
then F = ma.)
Post by Michal Jaegermann
Post by David C. Ullrich
(I don't know if you can pass a function as a parameter to
another function in Perl ....
Yes, you do. For standard examples of use look at 'perldoc -f sort' or
'man File::Find'. In such cases this ability is really important.
That's good.
Post by Michal Jaegermann
Michal
David C. Ullrich
Michal Jaegermann
2008-05-21 16:15:17 UTC
Permalink
Post by David C. Ullrich
I wish you'd actually _show_ me what it looks like.
I really do not think that comp.text.tex is a place for exercises in a
"tiny-bit-advanced" Perl; especially when they do not bring any new
ideas over what you already wrote. "Advanced" part comes in passing
as an argument a reference to a calculation routine. The rest is
a workout for beginners.

If you are so interested then try to write it yourself. One possibility
- interpolate variables and results of calculation into a "here
document" to produce a desired text. Quite simple.

There are other scripting languages which could be used for the same
task.
Post by David C. Ullrich
One reason being that it's not at all clear to me that more compact
would be a virtue
Shrug! Fishing expeditions in a pile of an irrelevant syntax
are no fun. Nobody proposed to write something for an obfuscated
Perl contest; although that is possible too.

Michal
David C. Ullrich
2008-05-22 11:11:49 UTC
Permalink
On Wed, 21 May 2008 16:15:17 +0000 (UTC), Michal Jaegermann
Post by Michal Jaegermann
Post by David C. Ullrich
I wish you'd actually _show_ me what it looks like.
I really do not think that comp.text.tex is a place for exercises in a
"tiny-bit-advanced" Perl; especially when they do not bring any new
ideas over what you already wrote.
I think it's too bad you feel that way. This may not be the place
for a language war, but I don't think that posting a snippet
of Perl that does the job would be at all out of place.

Because I really do think that the best solution to the OP's
problem would be to write code in some language that simply
writes some LaTeX. Because that wouldn't be hard, it would
give a much more flexible solution than various alternatives,
and once he'd done that he'd find he could use the same
language to solve other problems he hasn't even realized
he has.

_If_ he's going to do that then the choice of what language
to use makes some difference. So it seems to me it would be
a good thing if he could see a Python example and also see
a Perl example, so he could decide for himself which one
males more sense, as a hint regarding which language would
be easier to learn.
Post by Michal Jaegermann
"Advanced" part comes in passing
as an argument a reference to a calculation routine. The rest is
a workout for beginners.
Precisely one of my points. In Python if you want to pass a
function as a parameter to another function there's nothing
to figure out - you simply _pass_ the function as an
_argument_.
Post by Michal Jaegermann
If you are so interested then try to write it yourself.
But I haven't written a line of Perl in probably 10 years or so,
so it would take me much more time than someone who used
Perl all the time. (And back when I did know some beginning
Perl I never got to the write-code-just-about-as-fast-as-I-can-type
level...)

Also it wouldn't seem quite fair - I obviously have a bias
here, if the OP _was- going to see a Perl example for
comparison it should be written by someone who
thinks that Perl is the best way to do it.
Post by Michal Jaegermann
One possibility
- interpolate variables and results of calculation into a "here
document" to produce a desired text. Quite simple.
If you say so. Not seeing the actual code I can't tell whether
this would be as modular as the Python I gave, as opposed
to a solution where essentially the whole script has to be
revised each time we have a different exercise to typeset.

(I suspect it would be the latter, and I think the former is
a big plus. Exactly why that Perl should be written by
someone other than me.)
Post by Michal Jaegermann
There are other scripting languages which could be used for the same
task.
Post by David C. Ullrich
One reason being that it's not at all clear to me that more compact
would be a virtue
Shrug! Fishing expeditions in a pile of an irrelevant syntax
are no fun. Nobody proposed to write something for an obfuscated
Perl contest; although that is possible too.
Michal
David C. Ullrich
Michal Jaegermann
2008-05-22 16:16:13 UTC
Permalink
Post by David C. Ullrich
Precisely one of my points. In Python if you want to pass a
function as a parameter to another function there's nothing
to figure out - you simply _pass_ the function as an
_argument_.
So the difference is that if you have a subroutine named calculation
then in Python you write 'calculation' on an argument list and in Perl
you would need '\&calculation' in a similar place. As "advanced" in
Perl as in Python where passing a subroutine is also usually not
discussed in first lessons for beginners. OTOH using in such place an
anonymous routine is natural in Perl but not in Python. In a moment
we will be talking about closures...

That is why I do not think that a TeX discussion group is a place for
comparing syntax peculiarities of different scripting languages. You
demonstrated one possible implementation of ideas and that is good and
enough. Otherwise we will branch into minutae how to do that in awk
(really easy), or Scheme (even easier), or who knows in what. Doing
that entirely in TeX is also possible (withing appropriate ranges)
and here more interesting.

Consider that thread closed.

Michal

Loading...