如果數學表達式包含運算符,則將其括起來

如果數學表達式包含運算符,則將其括起來

想像一下,我已經寫了表格的幾個分數$\frac{V+W}{U}$,後來決定將它們顯示為斜線分數。在我希望這種情況發生的團隊中,我總是可以做到\renewcommand\frac[2]{#1/#2}。但是,我想在分子(或分母)中添加括號除非它包含一個mathop.至少,在我看來,這似乎是決定分子(分母)是否帶括號的合適的第一個啟發式。

有誰知道如何實現這一目標?

答案1

在這裡,我搜尋+-\bullet\cdot,但您可以向\setsepchar清單中添加更多運算符。

另外,如果運算子是前導的,例如-3,我不會加上括號。您可以透過註釋該行來更改它\ignoreemptyitems

編輯以解決一個奇怪的錯誤,當\sim它本身作為 的參數出現時\inlinefrac

\documentclass{article}
\usepackage{listofitems}
\newcommand\inlinefrac[2]{
  \setsepchar{+||-||\bullet||\cdot||\oplus}
  \ignoreemptyitems
  \readlist*\xator{ #1}
  \ifnum\listlen\xator[]>1\relax(#1)\else{#1}\fi
  /
  \readlist*\xator{ #2}
  \ifnum\listlen\xator[]>1\relax(#2)\else{#2}\fi
}
\begin{document}
\[
  \frac{2}{3}\quad\let\frac\inlinefrac\frac{2}{3}
\]
\[
  \frac{2}{-3}\quad\let\frac\inlinefrac\frac{2}{-3}
\]
\[
  \frac{2+x}{3}\quad\let\frac\inlinefrac\frac{2+x}{3}
\]
\[
  \frac{2\bullet x}{3\cdot y}\quad\inlinefrac{2\bullet x}{3\cdot y}
\]
\centering$\inlinefrac{M\oplus N}{\sim}$
\end{document}

在此輸入影像描述

答案2

我提出一個\ifrac命令。如果給出*它,它將調用,但它也會遵循(本地設定)\inlinefrac所做的設定。\fractionsinline

這樣,透過新增或刪除*.也可以\inlinefrac直接使用。

分子和分母中觸發括號的符號不必相同:乘法符號應僅觸發分母中的括號。

\documentclass{article}
\usepackage{amsmath}
\usepackage{xparse}

\ExplSyntaxOn

\NewDocumentCommand{\ifrac}{smm}
 {
  \IfBooleanTF { #1 }
   { \inlinefrac { #2 } { #3 } }
   {
    \bool_if:NTF \l_bubaya_frac_inline_bool
     {
      \inlinefrac { #2 } { #3 }
     }
     {
      \frac { #2 } { #3 }
     }
   }
 }

\bool_new:N \l_bubaya_frac_inline_bool

% extend the regex at will; \+ and \- stand for + and -,
% \c{command name} for a control sequence
\regex_const:Nn \c_bubaya_frac_num_regex { \+ | \- | \c{sin} | \c{cos} }
\regex_const:Nn \c_bubaya_frac_den_regex { \c{cdot} | \c{times} | \c{bullet} }

\NewDocumentCommand{\fractionsinline}{}
 {
  \bool_set_true:N \l_bubaya_frac_inline_bool
 }

\NewDocumentCommand{\inlinefrac}{mm}
 {
  \regex_match:NnTF \c_bubaya_frac_num_regex { #1 } { (#1) } { #1 }
  /
  \regex_match:NnTF \c_bubaya_frac_num_regex { #2 }
   {
    (#2)
   }
   {
    \regex_match:NnTF \c_bubaya_frac_den_regex { #2 } { (#2) } { #2 }
   }
 }

\ExplSyntaxOff

\begin{document}
\begin{gather*}
  \ifrac{2}{3}\qquad\ifrac*{2}{3}
\\
  \ifrac{2}{-3}\qquad\ifrac*{2}{-3}
\\
  \fractionsinline
  \ifrac{2}{-3}\qquad\ifrac{2}{-3}
\\
  \inlinefrac{2+x}{3}
\\
  \ifrac{\sin x}{x}\qquad\ifrac*{\sin x}{x}
\\
\end{gather*}

\fractionsinline
\begin{gather*}
  \ifrac{2+x}{3}
\\
  \ifrac{2\bullet x}{3\cdot y}
\\
  \ifrac{\sin x}{x}
\end{gather*}

\end{document}

在此輸入影像描述

答案3

與@Steven的解決方案具有相同想法的替代方案,但使用xstringpackage.json 。

\documentclass{article}
\usepackage{xstring}
\renewcommand\frac[2]{\IfSubStr{#1}{+}{(#1)}{\IfSubStr{#1}{-}{(#1)}{#1}}/\IfSubStr{#2}{+}{(#2)}{\IfSubStr{#2}{-}{(#2)}{#2}}}
\begin{document}
\(\frac{5}{10}=0.5\) but \(\frac{5+1}{10}=0.6\) and \(\frac{7}{10+4}=0.5\) but \(\frac{14+1}{6+1.5}=2\)
\end{document}

在此輸入影像描述

PS:我建議史蒂文的解決方案更容易擴展到更多情況,但在看到他的答案之前已經創建了此代碼,因此發布。

相關內容