简体   繁体   中英

Constraint behavior for a range of floating point numbers?

I was looking at this question for ideas on implementing a constraint/wrap for a given range.

From that I could ascertain the following

[n1, n2)

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

Which only works with positive numbers so this was advised

float Constrain(float x, float lo, float hi)
{
    float t = (x - lo) % (hi - lo);

    return t < 0 ? t + hi : t + lo;
}

I'm still uncertain how I can get the following range constraints from the above code and would like some help?

[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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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