对于需要确定性并在不同平台(编译器)上提供相同结果的程序,不能使用内置三角函数,因为计算它的算法在不同系统上是不同的。经测试,结果值不同。
(编辑:结果需要与在所有客户端上运行的游戏模拟中使用的最后一位完全相同。这些客户端需要具有完全相同的模拟状态才能使其工作。任何小的随着时间的推移,错误可能会导致越来越大的错误,并且游戏状态的 crc 被用作同步检查)。
所以我想出的唯一解决方案是使用我们自己的自定义代码来计算这些值,问题是,(令人惊讶的是)很难为所有三角函数集找到任何易于使用的源代码。
这是我对 sin 函数获得的代码 ( https://codereview.stackexchange.com/questions/5211/sine-function-in-cc ) 的修改。它在所有平台上都是确定性的,其值与标准 sin 的值几乎相同(均经过测试)。
#define M_1_2_PI 0.159154943091895335769 // 1 / (2 * pi)
double Math::sin(double x)
{
// Normalize the x to be in [-pi, pi]
x += M_PI;
x *= M_1_2_PI;
double notUsed;
x = modf(modf(x, ¬Used) + 1, ¬Used);
x *= M_PI * 2;
x -= M_PI;
// the algorithm works for [-pi/2, pi/2], so we change the values of x, to fit in the interval,
// while having the same value of sin(x)
if (x < -M_PI_2)
x = -M_PI - x;
else if (x > M_PI_2)
x = M_PI - x;
// useful to pre-calculate
double x2 = x*x;
double x4 = x2*x2;
// Calculate the terms
// As long as abs(x) < sqrt(6), which is 2.45, all terms will be positive.
// Values outside this range should be reduced to [-pi/2, pi/2] anyway for accuracy.
// Some care has to be given to the factorials.
// They can be pre-calculated by the compiler,
// but the value for the higher ones will exceed the storage capacity of int.
// so force the compiler to use unsigned long longs (if available) or doubles.
double t1 = x * (1.0 - x2 / (2*3));
double x5 = x * x4;
double t2 = x5 * (1.0 - x2 / (6*7)) / (1.0* 2*3*4*5);
double x9 = x5 * x4;
double t3 = x9 * (1.0 - x2 / (10*11)) / (1.0* 2*3*4*5*6*7*8*9);
double x13 = x9 * x4;
double t4 = x13 * (1.0 - x2 / (14*15)) / (1.0* 2*3*4*5*6*7*8*9*10*11*12*13);
// add some more if your accuracy requires them.
// But remember that x is smaller than 2, and the factorial grows very fast
// so I doubt that 2^17 / 17! will add anything.
// Even t4 might already be too small to matter when compared with t1.
// Sum backwards
double result = t4;
result += t3;
result += t2;
result += t1;
return result;
}
但我没有找到任何适合其他功能的东西,比如 asin、atan、tan(除了 sin/cos)等。
这些函数没有标准函数那么精确,但至少有 8 个数字会很好。