0

How can I define a variable, which is calculated from different variables, something like this:

\newcommand \varA {3}
\newcommand \varB {2}
\newcommand \varC {\varB*\varA}

So that \varC will conain 6 and not 3*2. This is important, since \varC will be used as a variable in text and in a pgfplot.

flobue
  • 3
  • 1

1 Answers1

3

If your aim is to use floating point numbers, pgfmath is not good. Look at the following example.

\documentclass{article}
\usepackage{xfp}
\usepackage{pgfmath}

\ExplSyntaxOn \NewDocumentCommand{\setvar}{mm} { \fp_zero_new:c { l_flobue_var_#1_fp } \fp_set:cn { l_flobue_var_#1_fp } { #2 } } \NewExpandableDocumentCommand{\usevar}{m} { \fp_use:c { l_flobue_var_#1_fp } } \ExplSyntaxOff

\begin{document}

\section{PGF}

\pgfmathsetmacro\varA{123.45} \pgfmathsetmacro\varB{0.012345} \pgfmathsetmacro\varC{\varA/\varB}

\verb|\varA| is \varA \ \verb|\varB| is \varB \ \verb|\varC| is \varC

\section{xfp}

\setvar{A}{123.45} \setvar{B}{0.012345} \setvar{C}{\usevar{A}/\usevar{B}}

\verb|A| is \usevar{A} \ \verb|B| is \usevar{B} \ \verb|C| is \usevar{C}

\setvar{B}{0.0012345} \setvar{C}{\usevar{A}/\usevar{B}}

\noindent Now \verb|C| is \usevar{C}; try with pgfmath

\end{document}

enter image description here

There are several advantages in the xfp approach with \setvar and \usevar:

  1. greater accuracy
  2. larger range
  3. no \pgfmathsetmacro that does no check about the command being defined
  4. greater flexibility

The fourth point is worth an example: if you need to use the result of the previous division, you can simply do

\fpeval{\usevar{A}/\usevar{B}}

and don't need to set another variable for getting the result expandably.

egreg
  • 1,121,712