我正在寻找一个如果给定的函数尚未声明则\pgfmathprovidefunction
执行的函数,如果它已经定义则不会报告错误(但不会更改现有的定义)。\pgfmathdeclarefunction
以下是我的黑客攻击似乎如果我总是使用,那么它可以正常工作\pgfmathprovidefunction
,但如果现有函数最初用\pgfmathdeclarefunction
它定义,则编译失败。
期望的输出是
参考:
代码:
\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}
答案1
宏\pgfmathdeclarefunction{F}
定义\pgfmath@function@F
,可用于检查函数是否已声明:
\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}