浮点数不能超过256?

Float can't go over 256?

我正在制作一个游戏,我在其中设置了一个带有浮标的位置,问题是浮标没有升高到 255? 这就是我如何使浮动更高: 1. 添加方法:

public Location add(float x, float y, float z){
    this.x += x; this.y += y; this.z += z;
    return this;
}

2。更新方式

public void update(){
        float speed = 0.00001f;
        float rotspeed = 0.00001f;
        if (Keyboard.isKeyDown(Keyboard.KEY_UP)) Main.renderer.rotate(-rotspeed, 0, 0);
        if (Keyboard.isKeyDown(Keyboard.KEY_DOWN)) Main.renderer.rotate(rotspeed, 0, 0);
        if (Keyboard.isKeyDown(Keyboard.KEY_RIGHT)) Main.renderer.rotate(0, rotspeed, 0);
        if (Keyboard.isKeyDown(Keyboard.KEY_LEFT)) Main.renderer.rotate(0, -rotspeed, 0);

        if (Keyboard.isKeyDown(Keyboard.KEY_W)) Main.renderer.renderLocation.add(0, 0, speed);
        if (Keyboard.isKeyDown(Keyboard.KEY_S)) Main.renderer.renderLocation.add(0, 0, -speed);
        if (Keyboard.isKeyDown(Keyboard.KEY_D)) Main.renderer.renderLocation.add(-speed, 0, 0);
        if (Keyboard.isKeyDown(Keyboard.KEY_A)) Main.renderer.renderLocation.add(speed, 0, 0);

        if (Keyboard.isKeyDown(Keyboard.KEY_SPACE)) Main.renderer.renderLocation.add(0, -speed, 0);
        if (Keyboard.isKeyDown(Keyboard.KEY_LSHIFT)) Main.renderer.renderLocation.add(0, speed, 0);
        fixRenderRotation();
    }

正在子线程的 while 循环中调用更新。

这就是我使用浮点数的原因

public void update(){
    System.out.println("render_location "+renderLocation.x+" "+renderLocation.y+" "+renderLocation.z+" rotation "+rotation.x+" "+rotation.y+" "+rotation.z);
    GL11.glClear(GL11.GL_COLOR_BUFFER_BIT | GL11.GL_DEPTH_BUFFER_BIT);
    GL11.glLoadIdentity();
    GL11.glTranslatef(renderLocation.x, renderLocation.y, renderLocation.z);
    //GL11.glTranslatef(renderLocation.x, renderLocation.y, renderLocation.z);
    GL11.glRotatef(rotation.x, 1F, 0F, 0F);
    GL11.glRotatef(rotation.y, 0F, 1F, 0F);
    GL11.glRotatef(rotation.z, 0F, 0F, 1F);
    ((RenderObject.UnknownRenderInformation) collection.getRenderInformation()).act();
}

这是 renderLocaiton 变量。 我不会阻止它继续走高。

float 只有 ~6 位数字的准确度。我建议使用 int 并除以 100,000 或使用 double

当您将 1e-5f 添加到 256f 时,答案是 256f,因为这是最接近的 represent-able 值。你对 double 有同样的问题,但要高得多。如果您将 1e-5 添加到 137438953472,当您超出 double.

的精度时,同样的事情也会发生

如果您使用 int,则会出现不同的问题。将 1 添加到 2147483647 并且 int 将溢出到 -2147483648

顺便说一句,你在达到 256 之前遇到了浮动问题。由于表示错误 128f + 1e-5f == 128.00002 我怀疑这不是你想要的。

事实上,如果您继续添加 1e-5f,则只需 65536 次即可在整数 value/whole 之间递增,而不是您可能预期的 100,000。

了解类型的限制很有用。

添加到 Peter 的回答中,这是必读的:What every computer scientist should know about floating-point arithmetic

基本上 256.00001f 会四舍五入为 256f(另一方面,255.00001f 会四舍五入为 255.00002f)。您可以存储 256.00002f,但它会四舍五入为 256.00003f。第一舍入 down 发生在 256.00001f 处,这就是您达到限制的位置,因此任何其他 0.00001 的添加都将无效(每次添加时,它都会因舍入而被丢弃)。您可能已经注意到,由于指数和尾数的工作方式,浮点数的小数点后五位并不是特别可靠,因此如果您想要更高的精度,请使用双精度数,但也不要期望它们具有完美的精度。