# \newcommand gives errors in math mode (with or without arguments)

I'm trying to define a custom command for use in math mode, defined as

\newcommand{\deriv2}[2]{\ensuremath{\frac{\partial^2 {#1}}{\partial {#2}^2}}}


Other non-math mode \newcommands work in my document, but as soon as I put one into math mode I get the error messages:

! LaTeX Error: Missing \begin{document}

! You can't use macro parameter character #' in math mode.


Now, I know one can roll their own commands to save tedium in math mode, and even pass arguments to them.

-
You can't define a command with a digit in its name –  egreg Feb 14 '12 at 15:32
You can't define commands with numbers in their name. –  Ulrike Fischer Feb 14 '12 at 15:34
Ok, so it really was a simple matter of syntax: dropping the '2' from '\deriv2' did fix it. Thanks for the swift responses to egreg and Ulrike Fischer! –  aejsk Feb 14 '12 at 15:47
What do we do with this question now? Close as too localised? –  Seamus Feb 14 '12 at 16:14
You could also use \pderiv[2]{...}{...} from cool. –  rdhs Feb 14 '12 at 16:33

Here is an alternative to your current situation - using an optional argument to specify the derivative order. This way you don't have to define a macro for "each" derivative:

\deriv[<order>]{<func>}{<var>}


Here's a minimal example:

\documentclass{article}
\newcommand{\deriv}[3][]{% \deriv[<order>]{<func>}{<var>}
\ensuremath{\frac{\partial^{#1} {#2}}{\partial {#3}^{#1}}}}
\begin{document}
In text mode there is~\deriv{y}{x} and~\deriv[2]{y}{x}. In display mode there is
$\deriv{y}{x}\ \textrm{and}\ \deriv[2]{y}{x}\rlap{.}$
\end{document}


The default <order> is empty, implying the first order partial derivative. If you want the default to be 2, modify the definition to read

\newcommand{\deriv}[3][2]{...}


Technically it is possible to use a macro with numbers in them, but the usage is much less intuitive than adding something like an optional argument (as given above). Here's an implementation that now allows you to use \nameuse{deriv2}{y}{x}:

\expandafter\def\csname deriv2\endcsname#1#2{%
\ensuremath{\frac{\partial^2 {#1}}{\partial {#2}^2}}}
\makeatletter
\newcommand{\nameuse}[1]{\@nameuse{#1}}%
\makeatother


The optional argument beats this hands down.

-

you can fool TeX and use the 2 as a parameter:

\newcommand\deriv[3]{\ensuremath{\frac{\partial^2 {#2}}{\partial {#3}^2}}}


now you can use \deriv2{x}{y}. But that works only when there is no \deriv command

-
This also only works for single-letter first-arguments. But who's interested in (say) the 11th-order partial derivative, right? ;)` –  Werner Feb 14 '12 at 19:39
did I said something different? –  Herbert Feb 14 '12 at 19:40