简体   繁体   English

有没有更有效的方法来包装浮点数?

[英]Is there a more efficient way to wrap a float?

I've been looking for examples on how to wrap a float between two numbers, similar to how you can do with integers using modulus.我一直在寻找有关如何在两个数字之间包装浮点数的示例,类似于如何使用模数处理整数。 Examples I've found either involve using fmod to just find the remainder past the decimal point, assuming it's for a circle and doing pi-based math, among other things that didn't quite do what I needed.我发现的例子要么涉及使用 fmod 来查找小数点后的余数,假设它是一个圆并进行基于 pi 的数学运算,除此之外,还没有完全满足我的需要。 Finally, I just wrote this:最后,我只写了这个:

float fwrap(float x, float a0, float a1)
{
    float mx = max(a0, a1);
    float mn = min(a0, a1);
    float nw = x;

    while(nw < mn) nw += mx - mn;
    while(nw > mx) nw -= mx - mn;
};

It works, but I'm sure if the original value is too far from the range, it'll slow thinks down, so is there a faster way to do this that doesn't involve loops?它有效,但我确定如果原始值离范围太远,它会慢慢思考,那么有没有更快的方法来做到这一点而不涉及循环?

All I need it to do is to wrap a number around a range when it goes beyond them, for instance, if a0 is 10 and a1 is 20, then if x is 25, it should return 15, but it should also work with floats, so if x is 8.5, it should return 18.5.我需要做的就是在超出范围时将数字环绕在一个范围内,例如,如果a0是 10, a1是 20,那么如果x是 25,它应该返回 15,但它也应该适用于浮点数,所以如果x是 8.5,它应该返回 18.5。

Is there a more efficient way to wrap a float?有没有更有效的方法来包装浮点数?

Use the fmod() family.使用fmod()系列。

#include <float.h>

float fwrap_alternate(float x, float min, float max) {
    if (min > max)
        return fwrap_alternative(x, max, min);
    return (x >= 0 ? min : max) + fmodf(x, max - min);
}

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

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