i have no problem getting random number and r and s but i didn't get naccept , nreject and ntrail.
i have no problem getting random number and r and s but i didn't get naccept , nreject and ntrail.
The following code correct(er):
I suggest you update the code because are sure using some non-standard stuff.Code:#include <stdlib.h> #include <stdio.h> #include <time.h> #define NUM 100 #define IMAX 10 #define ISEED 777861 #define ISEED1 777862 #define RND() ((double)rand()/(double)RAND_MAX) int main () { int i, naccept=0, nreject=0, ntrial=0, c; double x[NUM],s[NUM],r[NUM],pi; srand( time(NULL) ); naccept=0; nreject=0; ntrial=0; for (i=0; i<NUM; i++) { x[i]=RND(); } int j; double y[NUM]; //srandom(ISEED1); for (j=0; j<NUM; j++) { y[j]=RND(); } for (c=0; c<NUM; c++) { r[c]=x[c]*x[c]+y[c]*y[c]; printf("r=%f\n",r[c]); s[c]=r[c]*r[c]; printf("s[c]=%f\n",s[c]); if (s[c]<1.0){ naccept++; } else { nreject++; } } ntrial= naccept+nreject; printf("naccept=%d nreject=%d ntrail=%d\n",naccept,nreject,ntrial); pi=4.0*((double)naccept/(double)ntrial); printf("pi=%.3f\n",pi); }
It almost produces correct pi (ca 3.04x something I believe).
And only initialize the seed once.
hi Elysia , you are right it worked but it's not printing the value of pi
Thank you Elysia and ssharish
Sorry Elysia it worked
Thank you very much
This is my second program after learning c on my own. Can you please clarify those things . I am still confuse with rand and random stuff as well as seed.
Those stuff about %d and double.
Thanx,
When printing stuff with printf, you need to tell printf what type you're passing (it's not psychic).
%d tells printf the type is int. %f tells printf it's a double (or float).
And the random stuff works by initializing the seed once, and then calling rand. Rand will use the seed to generate random numbers. If you seed twice or more, you will see that you might actually get the same number as before (thus not really random).
%lf in C89 is undefined behavior. %lf in C99 is legal, but the l is ignored.