Generate a Random Number between 0 and 1
Last Updated :
13 Mar, 2023
The Task is to generate a random number between 0 and 1.
It is obvious that the number between 0 and 1 will be a floating point number. To generate a random number between 0 and 1, we will make use of the rand() function. The rand() function creates a random number.
Approach: Generating a Random Number between 0 and 1 with RAND_MAX value
RAND_MAX value is basically the maximum value that can be obtained by the rand() function. So, first of all, we will be using the srand() function for creating different values on every run.
Follow the steps mentioned below to implement the idea:
- Start a loop to check whether we are getting different random numbers on every iteration.
- Then, typecast the rand() function value in a double value as the number we want should be a decimal point number.
- inside the loop, we will output the random value obtained by rand() function divided by the RAND_MAX value.
- As the RAND_MAX value will be greater than the random number obtained by rand() function most of the time, we will get the result as '0.n'.
Below is the implementation of the above approach:
C++
// C++ code to implement the approach
#include <bits/stdc++.h>
using namespace std;
int main()
{
// Using srand() with time(0) to change
// the random values everytime
srand(time(0));
// Loop to check that we get different values
// on every iteration
for (int i = 0; i < 10; i++) {
// Typecasting the random value
// obtained into a double and
// then dividing it with RAND_MAX
cout << ((double)rand()) / RAND_MAX << endl;
}
return 0;
}
Java
/*package whatever //do not write package name here */
import java.io.*;
import java.util.Random;
import java.util.UUID;
class GFG {
public static void main (String[] args) {
for(int i = 0; i < 10; i++)
{
Random rand = new Random();
System.out.println(String.format("%.6f",
(double)Math.abs(rand.nextInt())/Integer.MAX_VALUE));
}
}
}
// This code is contributed by ksam24000.
C#
using System;
public class GFG {
static public void Main()
{
// Code
for (int i = 0; i < 10; i++) {
Random rand = new Random();
Console.WriteLine(string.Format(
"{0:F6}", (double)Math.Abs(rand.Next())
/ Int32.MaxValue));
}
}
}
// This code is contributed by lokeshmvs21.
JavaScript
// driver code
for(let i = 0; i < 10; i++)
{
document.write(Math.random())
}
// This code is contributed by garg28harsh.
Python3
import random
import time
random.seed(time.time())
for i in range(10):
print(random.random())
Output0.288481
0.338828
0.512149
0.810278
0.560978
0.683509
0.0417002
0.332409
0.0942754
0.938507
Time Complexity: O(1)
Auxiliary Space: O(1)
Another Approach:
The same thing can be done using INT_MAX instead of using RAND_MAX.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int main()
{
// using srand() with time(0) to change the random values everytime when the program
// is ran
srand(time(0));
// for loop to check that we get different values on every iteration
for (int i = 1; i < 11; i++) {
// typecasting the random value obtained into a double and then dividing it
// with INT_MAX
cout << ((double)rand()) / INT_MAX << endl;
}
}
Java
// Java code for above approach
import java.io.*;
import java.util.Random;
import java.util.UUID;
class GFG {
public static void main (String[] args) {
// for loop to check that we get different values on every iteration
for (int i = 1; i < 11; i++)
{
Random rand = new Random();
// typecasting the random value obtained into a double and then dividing it
// with INT_MAX
System.out.println(String.format("%.6f",
(double)Math.abs(rand.nextInt())/Integer.MAX_VALUE));
}
}
}
// This code is contributed by Pushpesh Raj.
C#
// C# code for above approach
using System;
class Program {
static void Main(string[] args)
{
// for loop to check that we get different values on
// every iteration
for (int i = 1; i < 11; i++) {
Random rand = new Random();
// typecasting the random value obtained into a
// double and then dividing it with int.MaxValue
Console.WriteLine("{0:F6}",
(double)Math.Abs(rand.Next())
/ int.MaxValue);
}
}
}
// This code is contributed by Prajwal Kandekar
Output0.645138
0.249392
0.313409
0.628442
0.491985
0.902581
0.400526
0.123816
0.397556
0.520698
Time Complexity: O(1)
Auxiliary Space: O(1)
Approach for generating a random number by defining a range:
The idea of this approach is that we will use the rand() function to get the random numbers between the defined range and then dividing it with a slightly larger number than the largest number in the defined range.
Follow the steps mentioned below to implement the idea:
- Run a loop and Inside the loop, set the rand() function to create a random number between the defined range.
- Then take range from 1 to 109. We are taking a big range of numbers as the number should not repeat most of the time.
- If the number repeats, we will get the same number between 0 and 1 every time the number repeats. Taking a small range of numbers will cause the program to output the same random values most of the time.
- After defining the range, we will be dividing the obtained number by n + 1, with n being the largest number in the defined range.
Below is the Implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
int main()
{
srand(time(0));
for (int i = 0; i < 10; i++) {
// defining a range of numbers and then dividing the obtained random number
// with the largest number in the range + 1
cout << ((double)(rand() % 100000000) + 1) / 100000001 << endl;
}
}
Output0.682537
0.213042
0.429056
0.583094
0.294206
0.327242
0.309042
0.165038
0.665797
0.542586
Time Complexity: O(1), since loop is traversed only from 1 to 10, and rand() method used O(1) time
Auxiliary Space: O(1), since only variables are created.
Similar Reads
How to generate a random number between 0 and 1 in Python ?
The use of randomness is an important part of the configuration and evaluation of modern algorithms. Here, we will see the various approaches for generating random numbers between 0 ans 1. Method 1: Here, we will use uniform() method which returns the random number between the two specified numbers
1 min read
Generate a Random Float Number in C++
Random floating numbers can be generated using 2 methods: Using rand()Using uniform real distribution1. Use of rand() We can generate random integers with the help of the rand() and srand() functions. There are some limitations to using srand() and rand(). To know more about the srand() and rand() f
5 min read
Program to generate a random number between L to R
Write a program that generates a random number within a specified range [L, R]. The program should take two integers, L and R, as input and output a random number between L and R (inclusive). Examples: Input: L = 10, R = 20Output: 15 Input: L = -5, R = 5Output: 3 Approach: To solve the problem, foll
2 min read
Program to generate a random three digit even number
Write a program to generate a random three-digit even number. Examples: Example 1: 482Example 2: 736 Approach: To solve the problem, follow the below idea: We can generate a random three-digit number by generating a random integer first and then modulo it by 900. Now, after modulo with 900, the rema
3 min read
Program to generate a random two-digit number
Write a program to generate a random two-digit number. Example 1: 73Example 2: 26 Approach: To solve the problem, follow the below idea: We can generate a random two-digit number by generating a random integer first and then modulo it by 90. Now, after modulo 90 the remainder can be in the range 0 t
2 min read
Generate random numbers and background colour in Django
In this article, we will learn how to generate random numbers and background colors in Python Django. And we will also see different steps related to a random number in Django. These are the following steps that we are going to discuss in this tutorial: What is the Django?Functions to generate a ran
3 min read
Program to generate a random single digit number
Write a program to generate a random single-digit number. Example 1: 7Example 2: 3 Approach: To solve the problem, follow the below idea: To generate a random single-digit number, we can first generate a random integer and then take apply modulo to get the last digit of that random integer. This las
2 min read
How to Generate Random Numbers in R
Random number generation is a process of creating a sequence of numbers that don't follow any predictable pattern. They are widely used in simulations, cryptography and statistical modeling. R Programming Language contains various functions to generate random numbers from different distributions lik
2 min read
How to Generate Unique Random Numbers in Excel?
Excel is powerful data visualization and analysis program we use to create reports or data summaries. So, sometimes happen that we have to create a report and assign a random id or number in a spreadsheet then we can create a random number without any repeat and manually.Approach 1: Using =RAND() f
1 min read
Generating Random Numbers in Golang
Golang provides a package math/rand for generating pseudorandom numbers. This package basically uses a single source that causes the production of a deterministic sequence of values each time a program is executed. Here, if you need different output or outcome for each execution, you can use the see
3 min read