-1

I want to generate random numbers between 0 and 1 (0 and 1 are included) but with only 3 fractions after the decimal point, like these:

0.000, 0.214, 0.523, 0.451, 0.102, 1.000

The aim of the three decimal is not for printing. I want to implement Monte Carlo technique to get the value of PI. So it is for if statement. As a result I want to assign the random value to a variable like this:

double x = 0.241;
Nano
  • 3
  • 4
  • Do they have to be uniformly distributed? Trivially, you could generate random number between 100 & 999 using `rand()` and divide by 1000. Depends whether this (poor) randomness is sufficient for you. – P.P Oct 18 '14 at 22:18
  • Be warned that a `double` is not able to *store* all fractions in just 3 decimals. Why not use integers and avoid the problem you seem to try to solve? (As it has hints of an [X-Y Problem](http://meta.stackexchange.com/questions/66377/what-is-the-xy-problem).) – Jongware Oct 18 '14 at 22:34
  • you could set the limits to 0...1000, then divide the result by 1000 to get the range 0.000 to 1.000 – user3629249 Oct 18 '14 at 23:16

2 Answers2

1

you can generate a random integer between 0 and 1000 and divide it to 1000

following c code generates desired random value

#include <time.h>
#include <stdlib.h>

srand(time(NULL));
double r = (double)(rand()%1001)/1000;
Alper Cinar
  • 861
  • 5
  • 12
  • in conclusion I want to do for loop million times and calculate how many the value 1.0 is generated. so that I want three fractions to increase the chance of 1.0 to appear. – Nano Oct 18 '14 at 22:58
  • Note that since RAND_MAX is not evenly divisible by 1001 this will lead to modulo bias. It won't be large, but it'll be there. – pjs Oct 18 '14 at 23:01
-1

Use a random function to calculare a random number between 0 and 1000, then divide it to 1000. Pay attention, when you use time function to generate random number you'll get the same number until the PC clock has the same value ex:

11:20:20 PM > generate random number: 10
11:20:20 PM > generate random number: 10
11:20:20 PM > generate random number: 10
11:20:21 PM > generate random number: 989

So, generate a number per second or find some hack (you can find it easly with google, a lots of answer on stackoverflow has been given)

Coletz95
  • 34
  • 5