# $Id: random.s 62 2005-10-11 02:42:57Z phf $ # # Simple SPIM/MIPS example illustrating a random number generator. # # The original generator is from Park and Miller, 1988; I based # my code on Wirth and Reiser, 1992 though. .text # marks the following as "code" main: jal random # call random function move $a0, $v0 # move result to $a0 for printing li $v0, 1 # operating system service "print_int" syscall # call the operating system la $a0, newline # load address of string to print li $v0, 4 # operating system service "print_string" syscall # call the operating system b main # loop forever... li $v0, 10 # operating system service "exit" syscall # call the operating system # Returns a random word in $v0. random: li $t0, 16807 # constant a li $t1, 2147483647 # constant m divu $t1, $t0 mflo $t2 # constant q := m DIV a mfhi $t3 # constant r := m MOD a lw $t4, seed # variable Z divu $t4, $t2 mflo $t5 # Z DIV q mfhi $t6 # Z MOD q mul $t5, $t5, $t3 # r*(Z DIV q) mul $t6, $t6, $t0 # a*(Z MOD q) subu $v0, $t6, $t5 # - bgtz $v0, okay addu $v0, $v0, $t1 okay: sw $v0, seed jr $ra # return .data # marks the following as "data" newline: .asciiz "\n" # newline character seed: .word 1 # seed for random numbers