Download code

Jump to: navigation, search

Back to Box-Muller_transform_(C)

Download for Windows: single file, zip

Download for UNIX: single file, zip, tar.gz, tar.bz2

box_muller.c

 1 /* The authors of this work have released all rights to it and placed it
 2 in the public domain under the Creative Commons CC0 1.0 waiver
 3 (http://creativecommons.org/publicdomain/zero/1.0/).
 4 
 5 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 6 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 7 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 8 IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 9 CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
10 TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
11 SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
12 
13 Retrieved from: http://en.literateprograms.org/Box-Muller_transform_(C)?oldid=7011
14 */
15 
16 #include <stdlib.h>
17 #include <math.h>
18 #include <time.h>
19 #include <stdio.h>
20 
21 double rand_normal(double mean, double stddev) {
22     static double n2 = 0.0;
23     static int n2_cached = 0;
24     if (!n2_cached) {
25         double x, y, r;
26 	do {
27 	    x = 2.0*rand()/RAND_MAX - 1;
28 	    y = 2.0*rand()/RAND_MAX - 1;
29 
30 	    r = x*x + y*y;
31 	} while (r == 0.0 || r > 1.0);
32         {
33         double d = sqrt(-2.0*log(r)/r);
34 	double n1 = x*d;
35 	n2 = y*d;
36         double result = n1*stddev + mean;
37         n2_cached = 1;
38         return result;
39         }
40     } else {
41         n2_cached = 0;
42         return n2*stddev + mean;
43     }
44 }
45 
46 int main() {
47     int buckets[20] = {0};
48     int i, j;
49 
50     srand(time(NULL));
51     for(i=0; i<500; i++) {
52         double val = rand_normal(10.0, 3.0);
53         int i = (int)floor(val + 0.5);
54         if (i >= 0 && i < sizeof(buckets)/sizeof(*buckets))
55             buckets[i]++;
56     }
57     for(i=0; i<sizeof(buckets)/sizeof(*buckets); i++) {
58         for(j=0; j<buckets[i]; j++) {
59             printf("#");
60         }
61         printf("\n");
62     }
63     return 0;
64 }
65 


hijacker
hijacker
hijacker
hijacker