Torus32 a = Torus32 b + Torus32 c 为什么代码里可以相加呢?会有自动模运算吗?
/ /想法:
//我们可能想用整数(2^32 3232来表示实环面的一个元素x ——加法、减法和整数组合是native操作
——modulo 1映射到mod 2^32,这也是native的!
这看起来比使用float/double好得多,因为在float/double中modulo 1完全不是自然的。
typedef int32_t Torus32
;
typedef __int32_t int32_t;
typedef signed int __int32_t;
Torus32其实是有符号整数字
-2147483648<=Torus32<=2147483647
以16位int为例说明。
首先你要明白,在内存中存放的数都是补码。
最小的数是-32768,补码是1000,0000,0000,0000。-1的补码是1111,1111,1111,1111
-32768-1=[-32768]+[-1]
=1000,0000,0000,0000+1111,1111,1111,1111
=0111,1111,1111,1111
=32767
最大值是32767,补码是0111,1111,1111,1111。1的补码是0000,0000,0000,0001
32767+1=0111,1111,1111,1111+0000,0000,0000,0001
=1000,0000,0000,0000
=-32768
代码验证:
int32_t a = pow(2,31)-1;
int32_t b = 1;
int32_t c= pow(2, 31);
cout <<"a: " <<a <<endl;
cout <<"c: " <<c <<endl;
cout <<"a+1: " <<a+1 <<endl;
cout <<"a+b: " <<a+b <<endl;
a: 2147483647
c: 2147483647
a+1: -2147483648
a+b: -2147483648