您在谈论的是一种unwrap
算法,它可以泛化(不特定于数字 360 ......您可以使用 m=2*pi 的弧度来实现)。这是javascript中的一个:
/* symmetric modulo:
* y = smod(x,m) = x+k*m where k is an integer,
* and y is always in the range [-0.5,0.5)*m
*/
function smod(x, m)
{
return x-((Math.floor(x/m + 0.5))*m);
}
/* unwrap:
* for all i, y[i] = x[i] + k*m where k is an integer,
* and for i > 0, the increment y[i]-y[i-1] is in the
* range [-0.5,0.5)*m as in smod().
*
* the "init" parameter is optional (default to 0)
* and specifies the starting value for the unwrap state.
*/
function unwrap(x, m, init)
{
var yi = init || 0;
var y = [];
for (i = 0; i < x.length; ++i)
{
yi += smod(x[i]-yi, m);
y[i] = yi;
}
return y;
}
这是一个示例输出:
js>unwrap([100, 200, 348, 359, 23, 37, 46, 10, 350, 190], 360)
100,200,348,359,383,397,406,370,350,190
另一个 m=100:
js>unwrap([99,1,7,60,80,22,30,20,90,88,61,23,2,87,50,12], 100, 1000)
999,1001,1007,960,980,1022,1030,1020,990,988,961,923,902,887,850,812
仅供参考:在 C/Java/等中。位扩展存在类似的算法,其中输入为 16 位,输出为 32 位,环绕模数 m = 65536 = 输入值的跨度。您不需要“smod”函数,只需使用签名数学:
typedef short int16_t;
typedef long int32_t;
// do typedefs as appropriate on your CPU
int32_t unwrap_extend(int32_t prev, int16_t input)
{
int16_t delta = input - prev;
return prev + delta;
}