将新单位命令定义为 `\si` 单位的导数

将新单位命令定义为 `\si` 单位的导数

在我的文档中,我需要使用大量不同的 SI 单位。为了方便打字,我通常将新命令定义为\newcommand{\unitmass}{\si{\kilogram}}或。然后我可以使用或 之\newcommand{\unitmomentum}{\si{\kilogram\meter\per\second}}类的命令来完成。这为我节省了很多打字工作。2.5\unitmass3.4\unitmementum

\si[2.5d-15]{\kilogram\meter\per\second}直到我需要(注意数字的科学符号)时才出现问题,这仍然需要我输入完整的内容。一种替代方法是只对数字使用数学符号,因为$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。我不会假装下面的代码是我的原创作品。称之为 Cargo-cult 编程,但我并不是需要家庭作业的学生。这是我的专业工作,我使用 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类似语法不是默认设置,因为我认为它不是最优的。

相关内容