对于需要确定性并在不同平台(编译器)上提供相同结果的程序,不能使用内置三角函数,因为计算它的算法在不同系统上是不同的。经测试,结果值不同。

(编辑:结果需要与在所有客户端上运行的游戏模拟中使用的最后一点完全相同。这些客户端需要具有完全相同的模拟状态才能使其工作。任何随着时间的推移,小错误可能导致越来越大的错误,并且游戏状态的 crc 被用作同步检查)。

所以我想出的唯一解决方案是使用我们自己的自定义代码来计算这些值,问题是(令人惊讶的是)很难为所有三角函数集找到任何易于使用的源代码。

这是我对 sin 函数获得的代码 ( https://codereview.stackexchange.com/questions/5211/sine-function-in-c-c ) 的修改。它在所有平台上都是确定性的,并且该值几乎与标准 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, &notUsed) + 1, &notUsed);
  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 个数字就好了。

最佳答案

我想最简单的方法是选择一个实现所需数学函数的自由运行时库:

  • FreeBSD
  • go ,需要音译,但我认为所有函数都有非汇编实现
  • MinGW-w64
  • ...

  • 只需使用他们的实现。请注意,上面列出的是公共(public)领域或 BSD 许可或其他一些自由许可。如果您使用代码,请确保遵守许可证。

    关于c++ - 三角函数计算的源代码,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23876260/

    10-11 23:15
    查看更多