Soift
Soift

Reputation: 177

Elegant way to add or subtract a fixed value depending on input

Bear with me for a minute.

I have a method that should add or subtract a fixed value, depending on a given input.

I know that my max value is 1.0f, the min value is 0.0f. The fixed value is 0.1f.

Now if the input value is 1.0f the method should subtract until the value is 0f. If the input value is 0f the method should add 0.1f until the value is 1.0f.

So a working method for 0f to 1f would be:

void Foo(float input) {
    float step = .1f;
    for (float i=0f; i<=1f; i += step) {
        input = i;
    }
}

Obviously I could have an if-statement checking the input value, but is there another way to achieve this within one method? I feel like I'm just missing a very basic arithmetical operation here.

Upvotes: 4

Views: 340

Answers (2)

pingul
pingul

Reputation: 3473

If you want to really avoid using an if statement at all for the step, you can actually derive it from the input directly. In turn you might get some extra numerical errors, but as you're using floats already this might not be of your concern.

void foo(float input)
{
    float step = (.5f - input)/5.f;
    do 
    {
        input += step;
    } while (input > 0.0f && input < 1.0f);
}

Running it on my machine gives me

foo(1.0f) --> -7.45058e-08
foo(0.0f) --> 1

Upvotes: 0

Cheng
Cheng

Reputation: 66

just a suggestion

I think step could be adjusted to be positive or negative based on the initial value, and use a do-while so it runs the first time, until it hits the final value.

Based on your code

void Foo(float input) {
    float step = input == 0f ? .1f : -0.1f;

    do 
    {
        input = input + step
    } while (input > 0f && input < 1.0f);
}

Upvotes: 5

Related Questions