简体   繁体   English

在Java中添加浮点值会减慢512

[英]Adding values to float in Java slows down at 512

This line is executing in a loop: 该行正在循环执行:

shape.setPosX(shape.getPosX() + (.005f * (float) getDelta()));

getDelta is the milliseconds passed since the last loop as a double, usually averaging at ~0.001. getDelta是自上一个循环以来经过的毫秒数,为两倍,通常平均为0.001。

setPosX accepts and stores the float value. setPosX接受并存储浮点值。

getPosX , as you can guess, returns the float value 如您所getPosX返回浮点值

When the shape is drawn I see it steadily move across the screen but once X hits 512 it slows down by what seems like a factor of 10. I can reproduce it 100% of the time so it's a pretty big blocker. 绘制形状时,我看到它稳定地在屏幕上移动,但是一旦X达到512,它就会减速10倍。我可以100%地复制它,因此它是一个很大的障碍物。

What could be going on here? 这可能是怎么回事?

The problem is that the float you are using have not enough number of digits of precision to represent the number. 问题是您使用的float没有足够的精度数字来表示该数字。 You can check this by telling Java to determine if ( 512f + 0.005f * 0.001f == 512f ) (it is true .) 您可以通过告诉Java确定是否( 512f + 0.005f * 0.001f == 512f )来进行检查(确实true

In 32-bit floating point numbers, the least significant bit for the mantissa for values between 256 and 512 is around .00003 which happens to be enough for your getDelta() to push over (which suggests that your assumption that the value averages at 0.001f might be wrong). 在32位浮点数中,尾数介于256和512之间的最低有效位约为.00003 ,这恰好足以使getDelta()推入(这表明您假设该值的平均值为0.001f可能是错误的)。 The least significant bit for the mantissa for values between 512 and 1024 doubles to .00006 (since the exponent part is one more). 尾数的最低有效位(介于512和1024之间)的值加倍至.00006 (因为指数部分又多了)。 Your getDelta returns something that rounds up around once every 5 time or so, thus the speed is slowed ten-fold. 您的getDelta返回的结果每5次左右会四舍五入一次,因此速度降低了十倍。

You can play around with float s here . 你可以在这里float

The solution to this is to make your number a double . 解决的办法是使您的人数double

Fun trivia: floating point arithmetics is causes Minecraft to behave funny in high coordinates. 趣味问答:浮点运算是导致Minecraft在高坐标下表现出有趣的行为。 The effects are described in this page , although the actual bug might just be integer overflow. 尽管实际的错误可能只是整数溢出,但在本页中描述了效果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM