一系列浮点数的约束行为



我一直在研究这个问题,以获得关于为给定范围实现约束/包装的想法。

由此,我可以确定以下

[n1,n2)

float Wrap(float x, float lo, float hi)
{
    return x % Math.Abs(lo - hi);
}

它只适用于正数,所以建议

float Constrain(float x, float lo, float hi)
{
    float t = (x - lo) % (hi - lo);
    return t < 0 ? t + hi : t + lo;
}

我仍然不确定如何从上面的代码中获得以下范围约束,希望得到一些帮助?

[n1,n2]

(n1,n2]

(n1,n2]

float constrainExclusiveInclusive(float x, float lo, float hi){
    float result = Constrain(x, lo, hi);
    if (result == lo){result = hi;}
    return result;
}

[n1,n2]

float constrainInclusiveInclusive(float x, float lo, float hi){
    float result = Constrain(x, lo, hi);
    if (result == lo){
        //somehow decide whether you want x to wrap to lo or hi
        if (moonIsInTheSeventhHouse()){
            result = lo;
        }
        else{
            result = hi;
        }
    }
    return result;
}

(n1,n2)

float constrainExclusiveExclusive(float x, float lo, float hi){
    float result = Constrain(x, lo, hi);
    if (result == lo){
        throw new ArgumentException("No answer exists for the given inputs");
    }
    return result;
}

最新更新