Floating point rand values - How?

Started by
10 comments, last by peck 21 years, 7 months ago
quote:Original post by Anonymous Poster
Even if division is faster, how can this:

double num = min + (rand() * (1.0 / RAND_MAX)) * (max - min);

be faster than this:

double num = min + (rand() / RAND_MAX) * (max - min);

when the first one has to do an extra operation, the multiplication.
Because RAND_MAX is a constant, and 1.0/RAND_MAX always leads to same result, so it can be safely precalculated by the compiler. Leading to (rand() * 0.0000000314159265358979) or something.
Advertisement
quote:Original post by cedricl
Bottom line: don't micro-optimize because the compiler knows better than you.
I beg to differ. There are some 'unsafe' operations that you can optimize better than the compiler can, since self-made optimizations may lead to slightly different results, but still unnoticeable in real applications.

For example, take the good old days when sin() and cos() were costly operations. Using sin-table could've boosted your application's inner loops dramatically but sin-table still was nothing but micro-optimization. So I dare you to show me a compiler that can do sin-tables itself as you claim compiler knows better than me .

Here I just (falsely) assumed that division would lead to different results than multiplying with 1/x, which would've disabled compiler's ability to make that decision.

[edited by - civguy on September 8, 2002 2:55:59 PM]

This topic is closed to new replies.

Advertisement