[Tex/LaTex] Substitute \frac for a slash (/) only on inline math mode

fractionsmath-mode

I was wondering if there is a way to have LaTeX interpret $\frac{a}{b}$ as $a/b$, but \[\frac{a}{b}\] as \[\frac{a}{b}\].

It is a little tedious to change a inline equation $a/b$ to a display equation \[\frac{a}{b}\] when doing changes to my text.

Best Answer

Loading amsmath naturally switches \frac to \tfrac when in "inline math" (or text style) and \dfrac under "display math" (or display style). This provides a better layout:

enter image description here

\documentclass{article}

\usepackage{amsmath}

\begin{document}

See $\frac{1}{2}$, or
\[
  \frac{1}{2} \quad e^{\frac{1}{2}}.
\]

\end{document}

However, you can update \frac to condition based on the style using \mathchoice:

enter image description here

\documentclass{article}

\let\oldfrac\frac% Store \frac
\renewcommand{\frac}[2]{%
  \mathchoice
    {\oldfrac{#1}{#2}}% display style
    {#1/#2}% text style
    {#1/#2}% script style
    {#1/#2}% script-script style
}

\begin{document}

See $\frac{1}{2}$, or
\[
  \frac{1}{2} \quad e^{\frac{1}{2}}.
\]

\end{document}

Given that (say) \frac{x+y}{x-y} will be set as x+y/x-y when in text style, and technically have an incorrect mathematical representation, one could venture one step further. That is, measure the numerator and denominator width, and set it inside brackets if necessary:

enter image description here

\documentclass{article}

\let\oldfrac\frac% Store \frac
\makeatletter
\newcommand{\groupit}[1]{(#1)}% To group...
\newcommand{\nogroupit}[1]{#1}% ...or not to group
\renewcommand{\frac}[2]{%
  \setbox\z@\hbox{$#1$}% Store numerator
  \setbox\tw@\hbox{$#2$}% Store denominator
  \ifdim\wd\z@>1em \let\groupornot@i\groupit\else\let\groupornot@i\nogroupit\fi% Measure numerator
  \ifdim\wd\tw@>1em \let\groupornot@ii\groupit\else\let\groupornot@ii\nogroupit\fi% Measure denominator
  \mathchoice
    {\oldfrac{#1}{#2}}% display style
    {\groupornot@i{#1}/\groupornot@ii{#2}}% text style
    {\groupornot@i{#1}/\groupornot@ii{#2}}% script style
    {\groupornot@i{#1}/\groupornot@ii{#2}}% script-script style
}
\makeatother

\begin{document}

See $\frac{1}{2}$ or $\frac{m}{x^2}$, or
\[
  \frac{1}{2} \quad e^{\frac{1}{2}} \quad e^{\frac{x+y}{x-y}}.
\]

\end{document}