简体   繁体   English

如何添加浮点数但将总数保持/包装在0..1的范围内?

[英]How to add floats but keep/wrap the total within the range 0..1?

I'm doing some animation on several alpha values and want to set the values relative to a reference value 我正在对几个Alpha值进行一些动画处理,并希望设置相对于参考值的值

obj1.alpha = refAlpha + 0.25f;
obj2.alpha = refAlpha + 0.75f;

If refAlpha is 0.5 for example then I want obj2.alpha to be 0.25 not 1.25. 例如,如果refAlpha是0.5,那么我希望obj2.alpha为0.25,而不是1.25。 What math function is there to do that? 有什么数学函数可以做到这一点?

The mod operator % will do the trick in terms of wrapping. mod运算符%将在包装方面发挥作用。 (it works on floats as well as ints). (它适用于浮点数和整数)。

obj1.alpha = (refAlpha + 0.25f) % 1f
obj2.alpha = (refAlpha + 0.75f) % 1f

public static void main(String[] args) {
  System.out.println(1.25f % 1f); // --> 0.25
}

Unfortunately, java doesn't quite implement mod to the mathematical definition. 不幸的是,java并没有完全实现mod的数学定义。 a % b returns a value in the range (-b, b) , as opposed to [0, b) . a % b返回(-b, b)范围内的值,而不是[0, b) If you are ever subtracting values, the result could therefore be negative. 如果您要减去值,则结果可能为负。 If this is a usecase you are worried about, consider creating a helper function to handle it: 如果这是您担心的用例,请考虑创建一个辅助函数来处理它:

public static float mod(float a, float b){
    return ((a % b) + b) % b;
}

This will make the result in the range [0,b) . 这将使结果在[0,b)范围内。

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

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