Open In App

Why Rand() function Always give the Same Value ?

Last Updated : 29 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Have you ever wondered why the rand() function always gives the same values each time we compile and run our code? well in this post we are going to discuss this phenomenon in brief.

First, let us discuss what is rand() function and what is its property.

What is Rand() in C++?

rand() function is an inbuilt function in C++ STL, which is defined in header file <cstdlib>. rand() is used to generate a series of random numbers. The random number is generated by using an algorithm that gives a series of non-related numbers whenever this function is called.
The rand() function is used in C++ to generate random numbers in the range [0, RAND_MAX).

RAND_MAX: It is a constant whose default value may vary between implementations but it is granted to be at least 32767.

Syntax of rand():

int rand(void);

Below is the implementation of the rand()

C++




// C++ program to demonstrate
// the use of rand()
#include <cstdlib>
#include <iostream>
using namespace std;
 
int main()
{
    // This program will create some sequence of
    // random numbers on every program run
    for (int i = 0; i < 5; i++)
        cout << rand() << " ";
 
    return 0;
}


Java




import java.util.Random;
// Nikunj Sonigara
public class Main {
    public static void main(String[] args) {
        // This program will create some sequence of
        // random numbers on every program run
        Random rand = new Random();
 
        for (int i = 0; i < 5; i++) {
            System.out.print(rand.nextInt() + " ");
        }
    }
}


C#




using System;
 
class Program
{
    static void Main()
    {
        // This program will create some sequence of
        // random numbers on every program run
 
        // Using the Random class in C# for generating random numbers
        Random random = new Random();
 
        for (int i = 0; i < 5; i++)
        {
            // Generating and printing a random number
            Console.Write(random.Next() + " ");
        }
 
        // Optional: To keep the console window open for user to see the result
        Console.ReadLine();
    }
}


Javascript




// JavaScript program to demonstrate the use of Math.random()
 
// This program will create some sequence of random numbers on every run
for (let i = 0; i < 5; i++) {
  // Generate a random number between 0 and 1 (exclusive of 1)
  // Multiply it by a sufficiently large number (e.g., 2147483648) to simulate the range of rand() in C++
  const randomNumber = Math.floor(Math.random() * 2147483648);
  console.log(randomNumber);
}


Python3




# Python program to demonstrate
# the use of random module
import random
 
# This program will create some sequence of
# random numbers on every program run
for i in range(5):
    print(random.randint(0, 2147483647), end=" ")


Output

1804289383 846930886 1681692777 1714636915 1957747793 













As we can see in the above code each time when we compile the code same numbers are generated.

Why Rand() function gives same output?

The working of rand depends upon seed value of rand which is ‘srand()’. In many C libraries, if srand() is not called before rand(), the random number generator is automatically seeded with a default value (often 1).

This means that without explicitly setting a seed using srand(), you’ll get the same sequence of random numbers every time you run your program. This behaviour is not ideal for scenarios where you want different random sequences on each program run.

How to generate different random values?

Use the result of a call to srand(time(0)) as the seed. However, time() returns a time_t value which varies every time and hence the pseudo-random number varies for every program call. 

Below is the code to generate different random numbers each time we compile:

C++




// C++ program to generate random numbers
#include <cstdlib>
#include <iostream>
#include <time.h>
using namespace std;
 
int main()
{
    // This program will create different sequence of
    // random numbers on every program run
 
    // Use current time as seed for random generator
    srand(time(0));
 
    for (int i = 0; i < 5; i++)
        cout << rand() << " ";
 
    return 0;
}


Java




import java.util.Random;
 
public class Main {
    public static void main(String[] args) {
        // This program will create different sequence of
        // random numbers on every program run
 
        // Use current time as seed for random generator
        Random rand = new Random(System.currentTimeMillis());
 
        for (int i = 0; i < 5; i++) {
            System.out.print(rand.nextInt() + " ");
        }
    }
}


Python




import random
import time
 
# This program will create a different sequence of
# random numbers on every program run
 
# Use current time as seed for random generator
random.seed(time.time())
 
for i in range(5):
    print(random.randint(0, 1000)),


C#




using System;
 
class MainClass {
    public static void Main (string[] args) {
        // This program will create a different sequence of
        // random numbers on every program run
 
        // Use current time as seed for random generator
        Random rand = new Random((int)DateTime.Now.Ticks);
 
        for (int i = 0; i < 5; i++) {
            Console.Write(rand.Next() + " ");
        }
    }
}


Javascript




// Import the seedrandom library
const seedrandom = require('./seedrandom');
 
// This program will create a different sequence of
// random numbers on every program run
 
// Use current time as seed for random generator
const seed = new Date().getTime();
Math.seedrandom(seed);
 
for (let i = 0; i < 5; i++) {
    console.log(Math.random());
}


Output

1819819358 635851420 2142795904 94222491 328793323 















Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads