通常在我的内部循环中,我需要以"回绕"的方式索引一个数组,这样(例如)如果数组大小是my_array[index % array_size]
,并且我的代码要求元素-2,那么它应该被赋予元素98.在许多高级语言(如Python)中,只需使用my_array[index % array_size]
就可以做到这一点,但是由于某些原因,C的整数算术(通常)向零舍入,而不是一致地向下舍入,因此,当第一个参数为负时,其模运算符返回负结果.
通常我知道index
不小于-array_size
,在这种情况下,我只做my_array[(index + array_size) % array_size]
.然而,有时这是不能保证的,对于这些情况,我想知道实现总是正模函数的最快方法.有几种不需要分支的"聪明"方法,例如
inline int positive_modulo(int i, int n) {
return (n + (i % n)) % n;
}
或
inline int positive_modulo(int i, int n) {
return (i % n) + (n * (i < 0));
}
Of course I can profile these to find out which is the fastest on my system, but I can't help w或rying that I might have missed a better one, 或 that what's fast on my machine might be slow on a different one.
So is there a standard way to do this, 或 some clever trick that I've missed that's likely to be the fastest possible way?
Also, I know it's probably wishful thinking, but if there's a way of doing this that can be auto-vect或ised, that would be amazing.