如何将浮点数增加到下一个0.5的倍数

huangapple go评论78阅读模式
英文:

How to increase a float to the next multiple of 0.5

问题

我想将我的 float 值增加到它之后的第一个0.5的倍数。

例如,如果我有:float x = 3.397; 我希望它变为:x = 3.5;。或者,如果我有:float x = 7.895; 它应该变为 x = 8.0;

英文:

I would like to increase my float value to the first multiple of 0.5 after it.

For example, if I have: float x = 3.397; I would like it to become: x = 3.5;. Or, if I have: float x = 7.895; it should become x = 8.0;.

答案1

得分: 1

简单明了,但在每个细节中都隐藏着错误。

float nextHalf(float x) {
    // 已更正为:long n = Math.round(x * 2.0) + 1;
    return (float) (Math.ceil(x * 2.0) / 2);
}

经过 @chux-ReinstateMonica 的更正。

由于舍入方法round/floor/ceil会以整数单位为目标进行舍入,对于0.5,必须先将数字乘以2,然后再除以2。

当然,由于浮点数中的指数在一些较大的数字中,连续数字之间的差异不再低于1.0,因此在这种情况下:

nextHalf(x) == nextHalf(x + 1.0)
英文:

Quite simple, but in every detail errors are hidden.

float nextHalf(float x) {
    // CORRECTED THIS: long n = Math.round(x * 2.0) + 1;
    return (float) (Math.ceil(x * 2.0) / 2);
}

With corrections due to @chux-ReinstateMonica.

As rounding methods round/floor/ceil target integer units of 1, for 0.5 one must first scale the numbers by a factor 2 and afterwards divide by 2.

Of course because of the incorporated exponent in a floating point number at some large numbers the difference between successive numbers is no longer below 1.0 so then

nextHalf(x) == nextHalf(x + 1.0)

huangapple
  • 本文由 发表于 2020年10月21日 23:35:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/64467016.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定