Skip to main content
Engineering LibreTexts

23.4: Example

  • Page ID
    54398
  • \( \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}}\)

    In order to generate different random number for successive executions, the seed must be initialized with a different set of seed values each time.

    The following example simulates the roll of two dice, which requires two random integer numbers, each between 1 and 6.

    program diceRoll
    
    implicit none
    integer :: m, die1, die2, pair
    real :: x
    integer :: i, n, clock
    integer, dimension(:), allocatable :: seed
    character(10) :: nickname
    
        call random_seed(size = n)
        allocate(seed(n))
        call system_clock(count=clock)
        seed = clock + 37 * (/(i-1, i=1, n)/)
        call random_seed(put = seed)
        deallocate(seed)
    
        call random_number(x)
        die1 = int(x*6.0) + 1
    
        call random_number(x)
        die2 = int(x*6.0) + 1
    
        write (*,'(2(a,1x,i1/),a,1x,i2)') "Dice 1:", die1, &
                    "Dice 2:", die2, "Dice Sum", (die1+die2)
    
    end program diceRoll
    

    Will generate different values each execution. For example, three executions of the example program are shown below:

    C:\fortran> dice
    Dice 1: 5
    Dice 2: 4
    Dice Sum  9
    
    C:\fortran> dice
    Dice 1: 2
    Dice 2: 4
    Dice Sum  6
    
    C:\fortran> dice
    Dice 1: 1
    Dice 2: 6
    Dice Sum  7
    
    C:\fortran>
    

    The dice values will be different for each execution.


    This page titled 23.4: Example 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?