C program not adding float correctly

荒凉一梦 提交于 2019-12-02 07:11:09

问题


I have a method that looks like this:

float * mutate(float* organism){   
    int i;
    float sign = 1;
    static float newOrg[INPUTS] = {0};

    for (i = 0;i<INPUTS;i++){
        if (rand() % 2 == 0) {
            sign = 1;
        } else {
            sign = -1;
        }
        float temp = (organism[i] + sign);
        printf("bf: %f af: %f diff: %f sign: %f sign2: %f temp: %f\n\n",
            organism[i], (organism[i] + sign), (organism[i] + sign)-organism[i],
            sign, sign+sign, temp);
        newOrg[i] = organism[i] + sign;
    }

    return newOrg;
}

When sign is not 0 the first two "%f"s are the same and the 3rd is 0, also putting the sum in a variable didn't help. This is baffling me! I can post full code if needed.

Output:

bf: 117810016.000000 af: 117810016.000000 diff: 0.000000 sign: 1.000000 sign2: 2.000000 temp: 117810016.000000

回答1:


Finite precision of float.

A typical float can only represent about 232 different numbers. 117,810,016.0 and 1.0 are two of them. 117,810,017.0 is not. So the C sum of 117810016.0 + 1.0 results in the "best" answer of 117810016.0.

Using a higher precision type like double often will extend the range of +1 exact math, but even that will not be exact with large enough values (typically about 9.0*10e15 or 253).

If code is to retain using float, suggest limiting organism[i] to values to the inclusive range or ±8,388,608.0 (223).

Perhaps can code simply use integer types for this task like long long.



来源:https://stackoverflow.com/questions/40658456/c-program-not-adding-float-correctly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!