c# - 需要使用 float 来提高性能但需要 double 计算

标签 c# optimization performance floating-point

MonoGame 是微软 XNA 的开源版本。它是构建跨平台游戏的框架。

它有许多数学类型,例如 Vector 和 Quaternion。

我对他们使用 double 和 float 的方式感到有点困惑。

到目前为止,我收集了以下信息:

  • 花车可能比 double 更有效;
  • double 比 float 有更高的精度。

这是一种让我很困惑的方法:

/// <summary>
/// Transforms a single Vector2, or the vector normal (x, y, 0, 0), by a specified Quaternion rotation.
/// </summary>
/// <param name="value">The vector to rotate.</param><param name="rotation">The Quaternion rotation to apply.</param>
public static Vector2 Transform(Vector2 value, Quaternion rotation)
{
  float num1 = rotation.X + rotation.X;
  float num2 = rotation.Y + rotation.Y;
  float num3 = rotation.Z + rotation.Z;
  float num4 = rotation.W * num3;
  float num5 = rotation.X * num1;
  float num6 = rotation.X * num2;
  float num7 = rotation.Y * num2;
  float num8 = rotation.Z * num3;
  float num9 = (float) ((double) value.X * (1.0 - (double) num7 - (double) num8) + (double) value.Y * ((double) num6 - (double) num4));
  float num10 = (float) ((double) value.X * ((double) num6 + (double) num4) + (double) value.Y * (1.0 - (double) num5 - (double) num8));
  Vector2 vector2;
  vector2.X = num9;
  vector2.Y = num10;
  return vector2;
}

为什么不在整个过程中使用 double float (例如,将 num1..num8 作为 double 表达式内联到 num9 和 num10 中)?

最佳答案

这里的重点是一系列的计算都在double中进行, 不将中间结果四舍五入为 float .这可能会导致最终的 float给定float,结果更接近无限精确算术的结果。输入。

32 位和 64 位浮点运算之间的性能差异很小。存储32位和存储64位的空间差别很大。

将存储每个值的字节数减半可能会对性能产生很大影响。它有效地将每个缓存的大小和每个数据传输路径的带宽加倍。

关于c# - 需要使用 float 来提高性能但需要 double 计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24475923/

相关文章:

perl - 我如何在执行的各个阶段进行 Perl CGI 性能测量、基准测试、时间测量?

python - 如何避免在 numpy 中基于数组的函数内迭代?

python - 如何使 Pandas 数据框 Fortran 类型有序

java - 如何提高 java 应用程序从 oracle 数据库中获取大数据的性能?

php - 哪个更快,array_key_exists 还是 array_search?

c# - 使用 Bootstrap 对 Kendo Window 的内容进行样式化

javascript - C#中设置Cookie并Jquery中访问

c# - 以 JSON 形式返回 Entity Framework 结果

c# - 通过反射获取事件

c - 如何优化此功能? (使用几乎所有的处理能力)