Optimizing loop by using floating point value as loop counter -
i need execute loop
while (x) y
for n times, large number. while y, loop body, rather quick, test x takes 70% of runtime.
i can calculate number of loop iterations n beforehand instead of using x condition, simple for-loop possible.
for (i=1 n) y
however, n might exceed maximum value integer can store on machine, not option. alternative, proposed use floating point variable f instead. n large, f cannot equal n. thus, calculate f largest floating point number smaller n. allows me run
for (i=1 f) y while (x) y
most of iterations not need test x everytime, last n-f do.
the question is: how implement for-loop 1 f? increasing counter or decreasing f 1 in each step not work, numerical error grow large. current solution is:
for (while f > maxint) (i=1 maxint) y f -= maxint while (x) y
is there better way solve problem?
what mean numerical error? floating point counting exact within precision. here maximum values representable integers using following data types:
uint32max = 4294967295 uint64max = 18446744073709551615 float32intmax = 16777216 float64intmax = 9007199254740992
every integer 0 max representable without numerical error.
as can see, largest count available uint64. next comes float64, uint32 , float32.
what happens when increment uint32=4294967295 ? 0.
what happens when increment float32=16777216 ? 16777216.
which better behavior?
have thought using 2-dimensional loop? if n ism maximum count 1-dimensional loop, n x n maximum 2-dimensional loop, etc. if maximum count less maxuint x maxuint, decompose number n such that:
n == m * maxuint + r;
where
m = n / maxuint; r = n - m * maxuint;
then
for (i = m; i--;) (j = maxuint; j--;) dostuff(); (i = r; i--;) dostuff();
if maxuint*maxuint not large enough count you, can add 3-, 4-, ... -dimensional loops.
Comments
Post a Comment