Forums
New posts
Search forums
Members
Current visitors
Log in
Register
What's new
Search
Search
Search titles only
By:
New posts
Search forums
Menu
Log in
Register
Install the app
Install
Forums
Archive
Archive
C Programming
rand in a closed interval on the ints
JavaScript is disabled. For a better experience, please enable JavaScript in your browser before proceeding.
You are using an out of date browser. It may not display this or other websites correctly.
You should upgrade or use an
alternative browser
.
Reply to thread
Message
[QUOTE="Frank Silvermann, post: 2468571"] [snipped away the other 95 percent] It was hard for me to determine what was relevant. Although I didn't use the SWAP macro for on the original post, I was glad to have it around to deal with the expected and unmathematical objection that they be reversed. #include <stdio.h> #include <stdlib.h> #include <time.h> #include <math.h> #define SWAP(m, n) (tmp = (m), (m) = (n), (n) = tmp) #define ITERATIONS 100 int rand_in_range(int, int); int main(void) { int tja, i , j, tmp, m, n; float mu; /* all declarations in main need to be north of here */ /* seed timer */ srand(time(NULL)); /* call rand */ j = 0; m = 40; n = 3; if (m > n) SWAP(m, n); printf("range is [%d, %d]\n", m, n); mu = (float)ITERATIONS *((float)m +(float)(m - n) /(float)2); printf("mu is %f\n", mu); for (i=0; i < ITERATIONS; i++) { tja = rand_in_range(m, n); if (i < 10) printf("return is %d\n", tja); j += tja; } printf("j is %d\n", j); return 0; } int rand_in_range(int m, int n) { /*seed srand in main */ /* [m, n] is range */ int t, top, diff, o, tmp; if (m == n) return m; if (m > n) SWAP(m, n); diff = n - m; top = RAND_MAX - (RAND_MAX % diff); /* control */ do t = rand(); while (t > top); o = t % (diff + 1) ; o = o + m; return o; } /* end source */ I think this is getting closer. The mu fiasco shows why it's sometimes hard to trim out of a function on the fly. If ITERATIONS is a positive power of ten, then the expected value is going to be the average of the two inputs with the decimal point moved. frank [/QUOTE]
Verification
Post reply
Forums
Archive
Archive
C Programming
rand in a closed interval on the ints
Top