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?

有帮助吗?

解决方案

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top