floating point - C program not adding float correctly -


i have method looks this:

float * mutate(float* organism){        int i;     float sign = 1;     static float neworg[inputs] = {0};      (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 not 0 first 2 "%f"s same , 3rd 0, putting sum in variable didn't help. baffling me! 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 

finite precision of float.

a typical float can represent 232 different numbers. 117,810,016.0 , 1.0 2 of them. 117,810,017.0 not. c sum of 117810016.0 + 1.0 results in "best" answer of 117810016.0.

using higher precision type double extend range of +1 exact math, not exact large enough values (typically 9.0*10e15 or 253).

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

perhaps can code use integer types task long long.


Comments

Popular posts from this blog

javascript - React Maximum Callstack when adding component -

javascript - Uncaught FirebaseError: Messaging: This method is available in a Window context -

correlation - Autocorrelation in Matlab WITHOUT xcorr -