Skip to main content
Engineering LibreTexts

23.2: Generating Random Number

  • Page ID
    54396
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \) \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)\(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\) \(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\)\(\newcommand{\AA}{\unicode[.8,0]{x212B}}\)

    To request a random number, a real variable must be declared and then passed to the following call to the built-in random_number() routine. For example:

    call random_number(x)
    

    The random number between 0.0 and 1.0 such that 0.0 \(\leq\) random number \(<\) 1.0.

    In order to obtain a larger number, it can be multiplied by an appropriate scale. For example, to simulating the roll of a dice, a random integer number between 1 and 6 would be required. The following code would obtain the random number and then scale it and convert to integer as required.

    call random_number(x)
    die = int(x*6.0) + 1
    

    Since the 0.0 is a possible value and 1.0 is not ( 0.0 \(\leq\) random number \(<\) 1.0) 1 is added to ensure that 0 cannot be assigned to the variable die. Further, since .999 is the largest possible value (since 1.0 is not), and .999 * 6 will generate 6 (5.9 truncated to 5 with 1 added).


    This page titled 23.2: Generating Random Number is shared under a CC BY-NC-SA 3.0 license and was authored, remixed, and/or curated by Ed Jorgensen via source content that was edited to the style and standards of the LibreTexts platform; a detailed edit history is available upon request.

    • Was this article helpful?