之前一直不太理解 rust 语言中原始类型中的数值类型取模运算(mod)和除运算(division)单独提供 rem_euclid
和 div_euclid
的原因。
数学定义:
$$ {\displaystyle {\begin{aligned}&q,r\in \mathbb {Z} \\&a=nq+r\\&|r|<|n|\end{aligned}}} $$
在编程语言中,实现除运算根据运算取整的时候采用何种策略来区分有五种实现。
Truncated division
$$ {\displaystyle q=\left[{\frac {a}{n}}\right]} $$
$$ {\displaystyle r=a-n\left[{\frac {a}{n}}\right]} $$
red: quotient (q) and green: remainder (r) as functions of dividend (a), using truncated division
Floored division
$$ {\displaystyle q=\left\lfloor {\frac {a}{n}}\right\rfloor } $$
$$ {\displaystyle r=a-n\left\lfloor {\frac {a}{n}}\right\rfloor} $$
red: quotient (q) and green: remainder (r) as functions of dividend (a), using floored division
$$ {\displaystyle q=\operatorname {sgn}(n)\left\lfloor {\frac {a}{\left|n\right|}}\right\rfloor ={\begin{cases}\left\lfloor {\frac {a}{n}}\right\rfloor &{\text{if }}n>0\\\left\lceil {\frac {a}{n}}\right\rceil &{\text{if }}n<0\\\end{cases}}} $$
$$ {\displaystyle r=a-|n|\left\lfloor {\frac {a}{\left|n\right|}}\right\rfloor } $$
red: quotient (q) and green: remainder (r) as functions of dividend (a), using euclidean division
Rounded division
$$ {\displaystyle q=\operatorname {round} \left({\frac {a}{n}}\right)} $$
$$ {\displaystyle r=a-n\operatorname {round} \left({\frac {a}{n}}\right)} $$
red: quotient (q) and green: remainder (r) as functions of dividend (a), using rounded division
Ceiled division
$$ {\displaystyle q=\left\lceil {\frac {a}{n}}\right\rceil } $$
$$ {\displaystyle r=a-n\left\lceil {\frac {a}{n}}\right\rceil } $$
red: quotient (q) and green: remainder (r) as functions of dividend (a), using ceiled division
我常用的语言中:
rem
和 div
采用的 Truncated division 实现方案。rem_euclid
和 div_euclid
采用的 Euclidean division 实现方案。rem( % )
和 div ( / )
采用的 Truncated division 实现方案。