在所有平台和处理器架构中,从float到int的转换是否一致? [英] Is conversion from float to int consistent across all platforms and processor architectures?

查看:124
本文介绍了在所有平台和处理器架构中,从float到int的转换是否一致?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个多人游戏,这个游戏取决于所谓的浮点确定性,换句话说,所有运行游戏的人都必须完全相同。这实际上意味着不使用IEEE 754浮点,因为操作可能会导致不同的值,具体取决于舍入模式,使用的融合乘加或反平方根指令,不同的libc实现等等。

所以我已经去了所有基本算术运算的定点版本,甚至是一些超验函数。不过,我仍然喜欢使用浮点文字来配置游戏玩法变量。在这样做的时候,我最终得到了一些看起来像这样的代码,将其从浮点转换为固定点:$ b​​
$ pre $ c $ explicit显式NetFixedPoint float val)
{
static const StorageType kOne = StorageType(1)<< FractionalBits;
m_Value =((StorageType)(val * kOne));



$ b $ p
$ b

在所有的平台和处理器体系结构中,简单的答案是否。

浮点数表示形式是

解决方案

实现已定义,并且在将浮点值转换为其他类型时,也会出现在浮点类型之间提及的关注类型。 另外,<$ c













$最终结果是,一些从 float int 的转换可以在实现之间可靠地工作,有些不会。将 float 转换为 int 时,一些值将被舍去。一个 float 也可以代表一个比 int 更大的值范围,并且转换超出范围值可以给未定义的行为。

与其尝试使用浮点文字来初始化变量,可以考虑使用字符串文本(并用双引号包装值)。权衡是解析字符串来初始化变量的开销。


I'm working on a multiplayer game that depends so called "floating point determinism", or in other words, the result of all calculations must be exactly the same across everyone running the game. This essentially means not using IEEE 754 floating point since operations can result in different values depending on rounding modes, fused multiply-add or inverse square root instructions being used, different libc implementations, etc etc.

So I've gone and made fixed point versions of all the basic arithmetic operations and even some transcendental functions. However I'd still like to use floating point literals for configuring gameplay variables. In doing so, I end up with some code that looks like this to convert from floating point to fixed point:

explicit NetFixedPoint(float val)
{
  static const StorageType kOne = StorageType(1) << FractionalBits;
  m_Value = ((StorageType)(val * kOne));
}

Will this give me the same result across all platforms and processor architectures?

解决方案

The short answer is "no".

Floating point representation is implementation defined, and the type of concerns you mention between floating point types also occur when converting floating point values to other types.

Also, a number of properties of int - including size, range of values it can represent, and representation (e.g. organisation of bits) are also implementation defined.

The net effect is that some conversions from float to int will work reliably between implementations, and some won't. Some values will be rounded down when converting float to int. A float can also represent a larger range of values than an int,and converting "out of range" values can give undefined behaviour.

Rather than trying to use floating point literals to initialise your variables, consider using string literals (and wrapping the values in double quotes). The tradeoff is overhead of parsing a string to initialise your variables.

这篇关于在所有平台和处理器架构中,从float到int的转换是否一致?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆