What is the uniform() method in D?

Overview

The random module is a part of the standard library in the D language. This module contains helpful functions to make random numbers as we may want. In this shot, we look at one of these functions known as the uniform() function.

What is the uniform function?

The uniform() function randomly returns any numbers X and Y, which serve as the lower and upper limit of random numbers that can be generated.

Let’s say we want to get any number between 10 and 20 at any time. Using the uniform() function, X, the lower limit, will be 10. Y, the upper limit, will be 20. This implies we will get a number Z in the range X <= Z < Y at any point this function is called.

Syntax

uniform(X, Y, randNumGen);

Parameters

  • X: This is of the int or float data type indicating the uniform distribution’s lower bound.
  • Y: This is of the int or float data type indicating the uniform distribution’s upper bound.
  • randNumGen: This function value can serve as the custom random number generator for the uniform() function based on another algorithm. However, it is optional. If it is not provided, the default rndGen is used.

Return value

The method returns a single randomly generated integer value.

Code

In the code below, we see an example where the uniform() function is used with two and three:

import std.stdio;
import std.random;
void main(){
/* random number generator*/
auto rand = Random();
writeln("With a random generator : ",uniform(2.5,40.6,rand));
writeln("Without a random generator : ",uniform(2.5,40.6));
}

Explanation

  • Line 1 and 2: We make some imports.
  • Line 4: We start the main function.
  • Line 6: We create a random number generator and give it a seed. With this seed of 4, the random number generated will not change unless the seed changes.
  • Line 8 and 9: We call the uniform() function and give it the parameters. Then, we print the result to display.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved