2

I have a library that modifies an input (adding or multiplying the input with one or more stored variables). These variables are stored as floats. Usually, the input is also a float, but in some cases it's an int. I'm concerned about the accuracy of this.

float GetValue(float input)
{
    foreach (float modifier in various_data_sources)
    {
        if (isFactor)
            input = input * modifier;
        else
            input = input + modifier;
    }
    return input;
}

void MainLogic()
{
    int defaultValue = 3;
    // If the modifier is 2 (add), I expect the final modified int to be 5:
    DoSomeIntThing((int) GetValue(defaultValue));
}

Is there anything I can do to make this safer? The value modifications need to be dynamic, and separating the modifications to integer operations and floating point operations will be a mess. Is this as unsafe as I think it is, or will an operation like (int)(2.0f+(float)3) always yield the hoped-for result?

11
  • What do you expect on an input of 3.5? Dec 3, 2013 at 6:29
  • 4
  • Can various_data_sources not be modified to store int for int operations? Then you could just use overloading.
    – Aron
    Dec 3, 2013 at 6:30
  • @MartinSmith I think your link could be quite easily expanded to a full answer (of No its not safe, for ints bigger than those numbers).
    – Aron
    Dec 3, 2013 at 6:34
  • 1
    Yeah, that's where it gets complicated. The JSON float is decimal, so it can actually say "1.5" and it means the same "1.5" you do. When saving, this is easy to achieve (float.ToString("f3") will ensure mostly correct rounding). When you load the value, you're converting it to base-2 "decimal" value => loss of precision. Many games actually use integers to do fixed point decimal math (for example, the Europa Universalis series uses integers with 3 decimal places). So you parse the input ("1" => 1000, "1.5" => 1500), and it will keep the decimal precison up to 3 decimal places.
    – Luaan
    Jan 21, 2014 at 10:05

1 Answer 1

1

Until your numbers are integer and have not more digits that a float mantissa can have, float operations on them are precise. The errors in counting floats appear because of cutting the ends. And while it doesn't happen it is nothing to be afraid of. But the first division by something different from a power of 2 will break this paradise. Or any operation that makes the result too long.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.