Skip to content

Instantly share code, notes, and snippets.

@kou1okada
Created April 2, 2013 14:41
Show Gist options
  • Save kou1okada/5292744 to your computer and use it in GitHub Desktop.
Save kou1okada/5292744 to your computer and use it in GitHub Desktop.
rand, srand - pseudo-random number generator of POSIX.1 example implementation for Ruby.
# Copyright (c) 2013 Koichi OKADA. All rights reserved.
# This script is distributed under the MIT license.
# http://www.opensource.org/licenses/mit-license.php
# rand, srand - pseudo-random number generator of POSIX.1 example implementation for Ruby.
# see
# Wikipedia / POSIX
# http://ja.wikipedia.org/wiki/POSIX
# The Linux man-pages project / rand(3)
# https://www.kernel.org/doc/man-pages/
# http://man7.org/linux/man-pages/man3/rand.3.html
# JM / rand(3)
# http://linuxjm.sourceforge.jp/
# http://linuxjm.sourceforge.jp/html/LDP_man-pages/man3/rand.3.html
# POSIX.1-2008 / XSH / rand
# http://pubs.opengroup.org/onlinepubs/9699919799/
# http://pubs.opengroup.org/onlinepubs/9699919799/functions/rand.html
module POSIX1
class Rand
def self.rand
DEFAULT.rand
end
def self.frand
rand() / (RAND_MAX + 1.0)
end
def self.srand seed
DEFAULT.srand seed
end
def initialize seed = nil
srand seed
end
def rand
@next = @next * 1103515245 + 12345
@next = (@next / 65536).floor % (RAND_MAX + 1)
end
def frand
rand / (RAND_MAX + 1.0)
end
def srand seed = nil
@next = seed.nil? ? Random.new.rand(RAND_MAX) : seed.to_i
end
RAND_MAX = 32767
DEFAULT = self.new
end
module_function
def rand
Rand.rand
end
def frand
Rand.frand
end
def srand seed = nil
Rand.srand seed
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment