c++ - 有没有更有效的方法来包装 float ?

标签 c++ performance math while-loop floating-point

我一直在寻找有关如何在两个数字之间包裹浮点的示例,类似于您可以使用模数对整数进行处理的示例。我发现的示例都涉及到使用fmod来查找小数点后的余数,假设它是一个圆并进行基于pi的数学运算,而其他事情并不能完全满足我的需要。最后,我只是这样写:

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;
};
它可以工作,但是我敢肯定,如果原始值与该范围相差太远,它将使思考速度变慢,因此,有没有一种更快的方法来执行此操作而不涉及循环?
我需要做的就是在超出范围时将数字包装在一个范围内,例如,如果a0为10且a1为20,那么如果x为25,则应返回15,但它也应与浮点数一起使用,因此,如果x为8.5,则应返回18.5。

最佳答案

Is there a more efficient way to wrap a float?


使用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);
}

关于c++ - 有没有更有效的方法来包装 float ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64271039/

相关文章:

c++ - 无法将类成员函数传递给另一个函数 (std::thread::thread)

c++ - boost 中是否有一个通用的 "clean-up"类?

python - 搜索名称并从大文件中提取相应的条目 - 最快的方法 - Python 和 Regex

JavaScript 性能 : Modulus operation of negative Number within decrementing loop slowing the code by more than 100%

c++ - cos泰勒级数展开的递归算法c++

math - 一维线段/范围相交测试 : Solution Name?

c++ - 面对使用指针的困难

c++ - 在系统编程和c++编程一样吗?

performance - Azure 存储表分区键和行键性能考虑更多唯一值

c# - 后缀和一元/二元运算符的中缀