[Tex/LaTex] \newcommand gives errors in math mode (with or without arguments)

macrosmath-modeoptional 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.

I have also tried defining my \newcommand without \ensuremath, and in all combinations of calling it within the equation environment, $$, and \[ \]. I've also tested it without the arguments #1 and #2, but any \newcommand I make seems to fail in math mode.

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

Best Answer

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:

enter image description here

\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.