Chinaunix首页 | 论坛 | 博客
  • 博客访问: 598353
  • 博文数量: 239
  • 博客积分: 7941
  • 博客等级: 准将
  • 技术积分: 2467
  • 用 户 组: 普通用户
  • 注册时间: 2010-07-10 12:14
个人简介

及时当勉励

文章分类

全部博文(239)

文章存档

2013年(29)

2011年(22)

2010年(188)

分类:

2010-04-13 22:55:57

/*
 * File: random.c
 * Version: 1.0
 * Last modified on Mon Sep 13 10:42:45 1993 by eroberts
 * -----------------------------------------------------
 * This file implements the random.h interface.
 */
#include
#include
#include
#include "genlib.h"
#include "random.h"
/*
 * Function: Randomize
 * -------------------
 * This function operates by setting the random number
 * seed to the current time.  The srand function is
 * provided by the library and requires an
 * integer argument.  The time function is provided
 * by .
 */
void Randomize(void)
{
    srand((int) time(NULL));
}
/*
 * Function: RandomInteger
 * -----------------------
 * This function first obtains a random integer in
 * the range [0..RAND_MAX] by applying four steps:
 * (1) Generate a real number between 0 and 1.
 * (2) Scale it to the appropriate range size.
 * (3) Truncate the value to an integer.
 * (4) Translate it to the appropriate starting point.
 */
int RandomInteger(int low, int high)
{
    int k;
    double d;
    d = (double) rand() / ((double) RAND_MAX + 1);
    k = (int) (d * (high - low + 1));
    return (low + k);
}
/*
 * Function: RandomReal
 * --------------------
 * The implementation of RandomReal is similar to that
 * of RandomInteger, without the truncation step.
 */
double RandomReal(double low, double high)
{
    double d;
    d = (double) rand() / ((double) RAND_MAX + 1);
    return (low + d * (high - low));
}
/*
 * Function: RandomChance
 * ----------------------
 * This function uses RandomReal to generate a number
 * between 0 and 100, which it then compares to p.
 */
bool RandomChance(double p)
{
    return (RandomReal(0, 1) < p);
}
阅读(2017) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~