[Tex/LaTex] How to define pgfmath local variables

pgfmath

When using pfgmathsetmacro in commands (defined by \newcommand) we have a problem of locality of variables. For instance if you design two functions

\newcommand\f[4]{%
  \pgfmathsetmacro#3{cosh(#1+#2)}%
  \pgfmathsetmacro#4{cos(#1+#2)}%
}
\newcommand\g[4]{%
  \pgfmathsetmacro#3{sqrt(1+(#1-#2)^2)}%
  \pgfmathsetmacro#4{sqrt((#1)^2+(#2)^2)}%
}

and want to define the composed function

\newcommand\h[4]{%
  \f#1#2\x\y%
  \g\x\y#3#4%
}

How do you protect the variables \x and \y such that you do not have to worry about not naming other variables \x or \y ?
If you have only one variable, the problem can be avoided using \pgfmathresult, but what if you have two (or more !) variables ?

Best Answer

I'll show a simplified version with one variable functions:

\documentclass{article}
\usepackage{tikz}

\newcommand\funcF[2]{%
  \pgfmathsetmacro#1{cosh(#2)}%
}
\newcommand\funcG[2]{%
  \pgfmathsetmacro#1{sqrt(#2)}%
}

\newcommand{\compose}[4]{%
  \begingroup
  #3\x{#4}%
  #2\x{\x}%
  \edef\x{\endgroup\noexpand\pgfmathsetmacro\noexpand#1{\x}}\x
}

\newcommand{\funcH}[2]{%
  \compose#1\funcG\funcF{#2}%
}

\begin{document}

\funcH\firstvalue{1}$\firstvalue$

\funcH\secondvalue{2}$\secondvalue$

\end{document}

The “local variable” \x is forgotten as soon as the final \x is executed.

enter image description here

Instead of \x you might want to use \AcOmMaNdNaMeThAtSpRoBaBlYnOtUsEd or something unusual like this.

Here's the response from bc -l, that shows that the functions are computed correctly, given the low precision with PGF:

> bc -l
bc 1.06
Copyright 1991-1994, 1997, 1998, 2000 Free Software Foundation, Inc.
This is free software with ABSOLUTELY NO WARRANTY.
For details type `warranty'. 
sqrt((e(1)+e(-1))/2)
1.24220796761864467541
sqrt((e(2)+e(-2))/2)
1.93963803094382315206
Related Question