將新單位指令定義為「\si」單位的派生詞

將新單位指令定義為「\si」單位的派生詞

在我的文件中,我需要使用大量不同的 SI 單位。為了簡化輸入,我通常將新命令定義為\newcommand{\unitmass}{\si{\kilogram}}\newcommand{\unitmomentum}{\si{\kilogram\meter\per\second}}。然後我可以使用類似2.5\unitmassor的東西3.4\unitmementum來完成。它節省了我很多打字的精力。

在我需要之前沒什麼問題\si[2.5d-15]{\kilogram\meter\per\second}(注意數字的科學記數法),這仍然需要我輸入完整的shebang。一種替代方法是僅對數字使用數學符號,因為$2.5\times 10^{-17}$\unitmomentum$這不是一個很好的選擇。理想情況下,我想要一些類似的事情\unitmomentum[2.5d-15]

這意味著,我必須以更複雜的方式定義我的命令,並且有數十個(迅速達到數百個)。因此,我必須定義一個接受命令的可選參數模板。

我的第一個方法是

\newcommand{\SimpleSIunit}[2]{%
    \expandafter\newcommand\csname #1\endcsname{\si{#2}}%
}

如果我保持滿足,沒有可選參數,它就會起作用。我可以發出幾十條指令,\SimpleSIunit{unittorque}{\newton\meter}這樣我的基本需求就被滿足了。

然而我真正想說的是

\newcommand{\SimpleSIunit}[2]{%
    \expandafter\newcommand[1][]\csname #1\endcsname{\si[##1]{#2}}%
}

這顯然沒有什麼好處。我有什麼想法可以糾正它嗎?

在我發音後\SimpleSIunit{unittorque}{\newton\meter},我希望這四行產生相同的輸出 -

2.5\unittorque
\unittorque[2.5]
2.5\si{\newton\meter}
\si[2.5]{\newton\meter}

** PS:: 在 @daleif 發表評論後編輯 **

在我做任何其他事情之前,間距由以下指令處理。它使用該savesym包。我不會假裝下面的程式碼是我的原創作品。稱之為貨物崇拜編程,但我不是需要作業的學生。這是我的專業工作,我使用 LaTeX 作為工具。

% spacing of siunits
\newlength{\siunitspace}
\sisetup{number-unit-product = \hspace{\siunitspace}}

% new units -- to act as supplement to SI units package \si{unit}
\input{unitdef-v01-2018} % a seperate file maintains this

\savesymbol{si}
\newcommand{\si}[2][?]{%
    \if\relax#1\relax%
    \hspace{\siunitspace}\origsi{#2}\xspace%
    \else%
    \if?#1\hspace{\siunitspace}\origsi{#2}\xspace\else\SI{#1}{#2}\xspace\fi%
    \fi%
}

答案1

內建了siunitx針對此類輸入的功能

\documentclass{article}
\usepackage{siunitx}
\sisetup{free-standing-units, ,unit-optional-argument, space-before-unit}
\DeclareSIUnit{\unitmomentum}{\kilogram\meter\per\second}
\begin{document}
Some text $3.5\unitmomentum$ and $\unitmomentum[2.5e-3]$.
\end{document}

請注意,這種units類似於語法的語法不是預設設置,因為我認為它不是最佳設定。

相關內容