Search code examples
mathlualimit

How to keep outputs of an operation between 2 set values? (limits,modulus)


I would like to write an operation that takes a number, that could take any value larger than -1, and only outputs a number between -1 and 0.5

Currently, I am able to ensure that the above happens and it always outputs a number between 0 and 1 by doing the following:

SupressedNumber = (Number)%1

And the following for values between -1 and 0:

SupressedNumber = (Number)%-1

And the following for values between -0.5 and 0:

SupressedNumber = (Number)%-0.5

However I would like to make it between -1 and <-0.5 (-0.49ish max). It doesn't have to use modulus but I feel like it's part of the solution. It just has to be doable in lua.


Solution

  • As far as I understand, you want to clamp a number between two values, but one of them is a supremum, not a maximum. Lets solve the first problem first:

    To clamp a number between two values inclusivly (e.g. -1 <= number <= -0.5), you can use the standard lua functions math.min() and math.max() or even code it yourself, if you need pure lua:

    local function clamp(min, value, max)
        return math.max(min, math.min(max, value))
    end
    

    clamp() will return value, but if value is smaller than min, it returns min. If it is greater than max, it returns max, so the result never leaves [-1, -0.5].

    Since your goal is: [-1, -0.5), you have to make a compromise. Computers store decimals with a finite amount of precision, so you can't get a number that is infinitly close to -0.5, but maybe a number, that is close enaugh. Let's create a variable epsilon which says, how close is close enough:

    local epsilon = 0.00001
    

    And now we can put both ideas together:

    supressed_number = clamp(-1, number, -0.5 + epsilon)
    

    This will clamp your number between -1 and a little bit less than -0.5:
    -1 <= value <= −0,49999 < -0.5