[Tex/LaTex] Math operators with and without parentheses

math-operatorsparenthesis

I have made several math operators in my preamble, but now I want to make a minor change (in the output). I will use the gradient operator as an example in the following. The MWE below shows my gradient definition including a small example of usage.

\documentclass{memoir} 

\usepackage{amsmath}
\usepackage{mathtools}

\DeclarePairedDelimiter\parentheses{\lparen}{\rparen}
\newcommand{\grad}[1]{\operatorname{grad} \parentheses*{#1}}

\begin{document}

\begin{align}
\grad{\vec{x}} = \grad{2y}
\end{align}

\begin{align}
\sin x = \sin (2y)
\end{align}

\end{document}

Currently, I always get parentheses in the ouput:
gradient

The problem is that I would like the left-hand side without parentheses, but still have parentheses on the right-hand side—depending on whether there is a single or multiple inputs/parameters, as exemplified for the sine:

sine

I would like to change this globally based on the above example without having to correct any operator notation throughout my document. Is that possible? Or optimal? And how is it best done in general (from scratch)?

(I would prefer automatic scaling of the parentheses.)

Best Answer

Based on a comment from Paul, my job actually became, perhaps, easier. Here, I do tests on the argument to \grad. If the argument is a single token (or embraced quantity) OR if it is \vec{<single token or embraced quantity>}, the parens are not employed. Otherwise, they are.

\documentclass{memoir} 
\usepackage{amsmath}
\usepackage{mathtools}
\usepackage{ifthen}
\DeclarePairedDelimiter\parentheses{\lparen}{\rparen}
\newcommand{\npgrad}[1]{\operatorname{grad} {#1}}
\newcommand{\pgrad}[1]{\operatorname{grad} \parentheses*{#1}}
\newcommand\grad[1]{\gradx#1\relax\relax\relax\relax}
\def\gradx#1#2#3\relax{%
  \ifx\relax#2\relax%
    \npgrad{#1}%
  \else
    \ifx\relax#3\relax%
      \ifx\vec#1\npgrad{#1{#2}}\else\pgrad{#1{#2}}\fi
    \else
      \pgrad{#1{#2}{#3}}%
    \fi
  \fi
}
\begin{document}

\begin{align}
\grad{\vec{x}}          &= \grad{2y}\\
\grad{\frac{2w}{y}}     &= \grad{\vec{z}}\\
\grad{p}                &= \grad{\vec{a}\times\vec{b}}\\
\grad{\vec{\mathcal{P}}} &= \grad{\alpha}
\end{align}
\end{document}

enter image description here

Related Question