模量给出错误的结果? [英] Modulus gives wrong outcome?

查看:88
本文介绍了模量给出错误的结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能告诉我为什么这两个模量计算会产生两个不同的结果?我只需要责怪某人或某物,但在失去这些错误的所有这些小时中,我都是我。

Could anyone tell me why these two modulus calculations yield two different outcomes? I just need to blame someone or something but me for all those hours I lost finding this bug.

public void test1()
{
    int stepAmount = 100;
    float t = 0.02f;
    float remainder = t % (1f / stepAmount);
    Debug.Log("Remainder: " + remainder);
    // Remainder: 0.01

    float fractions = 1f / stepAmount;
    remainder = t % fractions;
    Debug.Log("Remainder: " + remainder);
    // Remainder: 0
}

使用VS-2017 V15.3.5

Using VS-2017 V15.3.5

推荐答案

我最好的选择是,这是由于运行时的自由度使得其执行浮点运算的精度要高于类型。在分配时涉及到该类型的精度,然后将其截断为该类型的精度:

My best bet is that this is due to the liberty the runtime has to perform floating point operations with higher precision than the types involved and then truncating the result to the type's precision when assigning:


第12.1.3节中的CLI规范规定了浮点数的精确精度在存储位置中使用时,浮点和双精度数字。但是,当在其他位置(如执行堆栈,参数返回值等)中使用浮点数时,它允许超出精度。使用哪种精度留给运行时和基础硬件。这种额外的精度可能导致不同机器或运行时之间浮点评估的细微差别。

The CLI specification in section 12.1.3 dictates an exact precision for floating point numbers, float and double, when used in storage locations. However it allows for the precision to be exceeded when floating point numbers are used in other locations like the execution stack, arguments return values, etc … What precision is used is left to the runtime and underlying hardware. This extra precision can lead to subtle differences in floating point evaluations between different machines or runtimes.

来源此处

在您的第一个示例中 t%(1f / stepAmount)可以完全以比 float 更高的精度执行,然后在结果为分配给 remainder ,而在第二个示例中, 1f / stepAmount 被截断并分配给

In you first example t % (1f / stepAmount) can be performed entirely with a higher precision than float and then truncated when the result is assigned to remainder, while in the second example, 1f / stepAmount is truncated and assigned to fractions prior to the modulus operation.

为什么要使 stepamount a const 使两个模运算一致,原因是 1f / stepamount 立即成为一个常量表达式,该常量表达式将被求值并截断为float 编译时的精度,与编写 0.01f 并没有区别相当于安瓿。

As to why making stepamount a const makes both modulus operations consistent, the reason is that 1f / stepamount immediately becomes a constant expression that is evaluated and truncated to float precision at compile time and is no different from writing 0.01f which essentially makes both examples equivalent.

这篇关于模量给出错误的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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