2

I am looking for a \pgfmathprovidefunction which executes a \pgfmathdeclarefunction if the given function is not already declared and does not report an error if it was already defined (but does not change the existing definition).

My hack below seems to work fine if I always use \pgfmathprovidefunction, but if an existing function was originally defined with \pgfmathdeclarefunction it will fail compilation.

The desired output is

enter image description here

References:

Code:

\documentclass{article}
\usepackage{tikz}
\usepackage{etoolbox}

\def\pgfmathprovidefunction#1#2#3{% \ifcsdef{#1 Function Declared}{}{% \pgfmathdeclarefunction{#1}{#2}{#3}% \csgdef{#1 Function Declared}{}% }% }%

\pgfmathprovidefunction{MyFunction}{1}{% \pgfmathparse{0.5*pow(#1,2)}% }%

\pgfmathprovidefunction{MyFunction}{1}{% \pgfmathparse{0.5*pow(#1,3)}% }%

\begin{document} \begin{tikzpicture}[] \draw [ultra thick,blue,latex-latex, domain=-2:2] plot (\x,{MyFunction(\x)}); \end{tikzpicture} \end{document}

Peter Grill
  • 223,288
  • are you looking for something like the following? \makeatletter\def\pgfmathprovidefunction#1#2#3{\ifcsdef{pgfmath@function@#1}{}{\pgfmathdeclarefunction{#1}{#2}{#3}}}\makeatother – Sergei Golovan Aug 01 '19 at 07:09
  • @SergeiGolovan: Yep, that seems to work. Please post an answer. – Peter Grill Aug 01 '19 at 07:16

1 Answers1

5

The \pgfmathdeclarefunction{F} macro defines \pgfmath@function@F, which can be used to check if a function is already declared:

\documentclass{article}
\usepackage{tikz}
\usepackage{etoolbox}

\makeatletter
\def\pgfmathprovidefunction#1#2#3{%
    \ifcsdef{pgfmath@function@#1}{}{%
        \pgfmathdeclarefunction{#1}{#2}{#3}%
    }%
}%
\makeatother

\pgfmathdeclarefunction{MyFunction}{1}{%
      \pgfmathparse{0.5*pow(#1,2)}%
}%

\pgfmathprovidefunction{MyFunction}{1}{%
      \pgfmathparse{0.5*pow(#1,3)}%
}%

\begin{document}
\begin{tikzpicture}[]
      \draw [ultra thick,blue,latex-latex, domain=-2:2] plot (\x,{MyFunction(\x)});
\end{tikzpicture}
\end{document}