3

I would like to generate a random, real number in the interval [0,1]. I would like to set a pointer, say n, for the number so whenever I stated n, it will be referred to the random generated number.

I have searched on StackOverflow and on Google, but most of them are for C++ or for integers.

I have tried this code suggested to me in the answers:

#include <stdio.h>
#include <stdlib.h>
int main()
{
 double n;
double get_random() { return (double)rand() / (double)RAND_MAX; }
n = get_random();
printf("%f", n);
   return 0;
}

However, I can only get a value 0.00000000.

How could I fix my program?

Idos
  • 15,053
  • 14
  • 60
  • 75
Marcus.S
  • 43
  • 1
  • 1
  • 5
  • 1
    Does your compiler complain when you try to `printf` an `unsigned int` using `%f`? Perhaps you meant to declare `r` as a `double` instead. – e0k Jan 31 '16 at 17:53
  • Your `while` loop is ineffective, since `y = RAND_MAX + 1` the return value from `rand` will always be `< y`. – Weather Vane Jan 31 '16 at 18:04
  • Could you please elaborate on what you mean by "I would like to set a pointer, say n, for the number so whenever I stated n, it will be referred to the random generated number"? How is this not just a simple pointer assignment? – e0k Jan 31 '16 at 18:10
  • You can scale the unsigned `rand` value to a real number in your range, but the values will not be uniformly distributed as you requested. The granularity is still the same: only `RAND_MAX` different values will be generated. – Weather Vane Jan 31 '16 at 18:10
  • Sorry about not being clear... I am a beginner for C programming, so I just go google and found the rand() command... – Marcus.S Jan 31 '16 at 18:14
  • e0k: Thanks for your reply. What i mean is to define a double n, where n is equal to the randomly generated number from 0 to 1. – Marcus.S Jan 31 '16 at 18:15
  • Weather Vane : Thanks for your reply. How can I actually control the range of the rand()? I tried to type in the range inside the () or follow the instruction from the C FAQ centre, typing them after the rand() command. However, none of them works... – Marcus.S Jan 31 '16 at 18:17
  • I advise you to read the man page for any function that is new to you. *"The rand function returns a pseudorandom integer in the range 0 to RAND_MAX (32767). Use the srand function to seed the pseudorandom-number generator before calling rand."*. You can scale it as the answer below, where `double n` is assumed. – Weather Vane Jan 31 '16 at 18:19
  • Thanks Weather, i will go have a look on man page. Then i can just print the n out and see the value right? – Marcus.S Jan 31 '16 at 18:35
  • See above comments, with `printf` you have to match the format specifier with the variable type. – Weather Vane Jan 31 '16 at 18:36
  • Ya, I have defined and finally succeed in printing n out. Thanks! – Marcus.S Jan 31 '16 at 18:41

2 Answers2

7

You can use:

#include <time.h>
srand(time(NULL)); // randomize seed
double get_random() { return (double)rand() / (double)RAND_MAX; }
n = get_random();

srand() sets the seed which is used by rand to generate pseudo-random numbers. If you don't call srand before your first call to rand, it's as if you had called srand(1) (serves as a default).

If you want to exclude [1] use:

(double)rand() / (double)((unsigned)RAND_MAX + 1);

Full solution:

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

double get_random() { return ((double)rand() / (double)RAND_MAX); }

int main()
{
    double n = 0;
    srand(time(NULL)); // randomize seed
    n = get_random(); // call the function to get a different value of n every time

    printf("%f\n", n);  // print your number
    return 0;
}

Every time you run it you will get a different number for n.

Idos
  • 15,053
  • 14
  • 60
  • 75
  • 1
    Thanks Idos. I don't know who gave the downvote though... I still don't have the ability to upvote cause I dont have 15 reputation yet... I did then try to print n out, but, I have tried like over tens time, and the answer is always 0.001215 Is that because the n lose it's randomness after being defined? – Marcus.S Jan 31 '16 at 18:39
  • I will edit my answer so you can each time get a new value for n. Try it now, every time you call get_random() you will get a new different number – Idos Jan 31 '16 at 18:42
  • Idos, it is still giving 0.001215 for the result... Should I add a ; after the {} for the definition of get_random() to make it functional? – Marcus.S Jan 31 '16 at 18:50
  • No, that is a function... can you show exactly how you call the function? Please edit your question with that. it shouldn't give you the same number I checked it myself – Idos Jan 31 '16 at 18:50
  • You have to define your function outside the scope of main(). Let me edit my answer with a **full** solution so it will work for you – Idos Jan 31 '16 at 18:55
  • 1
    I see... Thanks Idos, this helps me a lot... I will try to learn more on C and the usage of function outside the main loop.... Thank you very much ! – Marcus.S Jan 31 '16 at 18:57
  • 1
    @Idos : C is a *procedural language*; [*functional language*](https://en.wikipedia.org/wiki/Category:Functional_languages) has a specific meaning in computer science, and C is not one. – Clifford Jan 31 '16 at 20:19
  • This is not uniformly distributed, and C does not provide any such implementation. There are libraries available that do, however. – Jimmio92 Oct 03 '21 at 18:24
0

This shows how to get random real numbers in the range 0..1 but please note that they are not uniformly distributed. There are only (RAND_MAX+1) discrete values.

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

int main(void) {
    int i;
    double n;
    srand((unsigned)time(NULL));            // seed the random num generator ONCE only
    for(i = 0; i < 3; i++) {                // get 3 random numbers
        n = (double)rand() / RAND_MAX;      // in the range 0 ... 1
        printf("%f\n", n);                  // use correct format specifier for the var
    }
    return 0;
}

My program output:

0.622608
0.814081
0.878689
Weather Vane
  • 33,872
  • 7
  • 36
  • 56