`
ant04444
  • 浏览: 23026 次
  • 性别: Icon_minigender_1
  • 来自: 广州
最近访客 更多访客>>
社区版块
存档分类
最新评论

Generate random numbers

    博客分类:
  • java
 
阅读更多
There are two means of generating random (really pseudo-random) numbers :
the Random class generates random integers, doubles, longs and so on, in various ranges.
the static method Math.random generates doubles between 0 (inclusive) and 1 (exclusive).
To generate random integers :
do not use Math.random (it produces doubles, not integers)
use the Random class to generate random integers between 0 and N.
To generate a series of random numbers as a unit, you need to use a single Random object - do not create a new Random object for each new random number. See also the related Sun Tech Tip.

Another alternative is SecureRandom, a cryptographically strong subclass of Random.

Example 1

import java.util.Random;

/** Generate 10 random integers in the range 0..99. */
public final class RandomInteger {
 
  public static final void main(String... aArgs){
    log("Generating 10 random integers in range 0..99.");
   
    //note a single Random object is reused here
    Random randomGenerator = new Random();
    for (int idx = 1; idx <= 10; ++idx){
      int randomInt = randomGenerator.nextInt(100);
      log("Generated : " + randomInt);
    }
   
    log("Done.");
  }
 
  private static void log(String aMessage){
    System.out.println(aMessage);
  }
}


Example run of this class :
Generating 10 random integers in range 0..99.
Generated : 44
Generated : 81
Generated : 69
Generated : 31
Generated : 10
Generated : 64
Generated : 74
Generated : 57
Generated : 56
Generated : 93
Done.
Example 2

This example generates random integers in a specific range.

import java.util.Random;

/** Generate random integers in a certain range. */
public final class RandomRange {
 
  public static final void main(String... aArgs){
    log("Generating random integers in the range 1..10.");
   
    int START = 1;
    int END = 10;
    Random random = new Random();
    for (int idx = 1; idx <= 10; ++idx){
      showRandomInteger(START, END, random);
    }
   
    log("Done.");
  }
 
  private static void showRandomInteger(int aStart, int aEnd, Random aRandom){
    if ( aStart > aEnd ) {
      throw new IllegalArgumentException("Start cannot exceed End.");
    }
    //get the range, casting to long to avoid overflow problems
    long range = (long)aEnd - (long)aStart + 1;
    // compute a fraction of the range, 0 <= frac < range
    long fraction = (long)(range * aRandom.nextDouble());
    int randomNumber =  (int)(fraction + aStart);   
    log("Generated : " + randomNumber);
  }
 
  private static void log(String aMessage){
    System.out.println(aMessage);
  }
}


An example run of this class :
Generating random integers in the range 1..10.
Generated : 9
Generated : 3
Generated : 3
Generated : 9
Generated : 4
Generated : 1
Generated : 3
Generated : 9
Generated : 10
Generated : 10
Done.
Example 3

This example generates random floating point numbers in a Gaussian (normal) distribution.

import java.util.Random;

/**
Generate pseudo-random floating point values, with an
approximately Gaussian (normal) distribution.

Many physical measurements have an approximately Gaussian
distribution; this provides a way of simulating such values.
*/
public final class RandomGaussian {
 
  public static void main(String... aArgs){
    RandomGaussian gaussian = new RandomGaussian();
    double MEAN = 100.0f;
    double VARIANCE = 5.0f;
    for (int idx = 1; idx <= 10; ++idx){
      log("Generated : " + gaussian.getGaussian(MEAN, VARIANCE));
    }
  }
   
  private Random fRandom = new Random();
 
  private double getGaussian(double aMean, double aVariance){
      return aMean + fRandom.nextGaussian() * aVariance;
  }

  private static void log(Object aMsg){
    System.out.println(String.valueOf(aMsg));
  }
}


An example run of this class :
Generated : 99.38221153454624
Generated : 100.95717075067498
Generated : 106.78740794978813
Generated : 105.57315286730545
Generated : 97.35077643206589
Generated : 92.56233774920052
Generated : 98.29311772993057
Generated : 102.04954815575822
Generated : 104.88458607780176
Generated : 97.11126014402141
分享到:
评论

相关推荐

    Matlab-to-generate-random-numbers.zip_产生泊松过程_伯努利_泊松随机数_随机数 产生_随机

    在提供的文档"Matlab to generate random numbers in the random process implementation.doc"中,可能会详细讲解如何在实际应用中使用上述函数,以及如何分析生成的随机数,例如验证其是否符合期望的分布,这通常会...

    JavaProgramToGenerateRandomNumbers.pdf 英文原版

    Java Program To Generate Random Numbers

    NAG Fortran Libraries

    * Generate random numbers * Simple calculations of statistical data * Analysis of correlation and regression * Multidimensional methods * Variance analysis * Analysis of the time series * Non-...

    RandomNumber

    采用C++语言产生伪随机数,可以选择产生整数随机数和小数随机数 (Generating pseudo-random numbers in C++ language ,You can choose to generate integers, random numbers, and decimal random numbers)

    项目七概率论-数据统计与区间估计(完整版)实用资料.doc

    We will learn how to use Mathematica to generate random numbers, visualize the results, and calculate the frequency and probability of different outcomes. 在这个实验中,我们学习了如何使用 ...

    mmap-basic.rar_The Test

    This test will generate random numbers of calls to some getpid syscalls, then establish an mmap for a group of events that are created to monitor the syscalls.

    senor-octopus:流媒体中心。 有点

    # generate random numbers and send them to "check" and "normal" [random] plugin = source.random flow = -&gt; check, normal schedule = * * * * * # filter numbers from "random" that are &gt; 0.5 and send to ...

    R for beginner

    - **Random Sequences**: Functions like `rnorm()`, `runif()`, etc., can be used to generate random numbers following specific distributions. ##### Manipulating Objects R offers a wide range of ...

    rayleigh.rar_数值算法/人工智能_C/C++_

    描述中提到的"A C code to generate random numbers and find its histogram"确认了这是一个生成随机数并绘制其直方图的C语言程序,这通常是为了分析数据分布,比如瑞利分布。 瑞利分布是一种统计分布,常见于物理...

    python的随机数生成包,1-15的3个不重复随机数字

    random_numbers = generate_unique_random_numbers(3, 1, 15) print(random_numbers) ``` 这段代码首先定义了一个名为`generate_unique_random_numbers`的函数,该函数接受三个参数:要生成的随机数数量`n`,以及...

    chi-square-test.rar_By The Numbers_Chi-Sqaure_chi square test_ch

    This report describes the transformation techniques to generate non-uniform random numbers with the exponential, normal and arbitrary distributions. These are generated by random number generator, ...

    产生10个随机两位数

    这段代码定义了一个函数`generate_even_random_numbers`,它会生成指定数量(默认为4)的两位偶数。在循环中,我们首先生成一个随机的两位数,然后检查它是否是偶数。如果是,就将其添加到结果列表中。当列表长度...

    4个英文字母的验证码

    numbers = generate_random_numbers() captcha = numbers_to_letters(numbers) return make_case_insensitive(captcha) ``` 5. **窗口事件处理**:如果是在图形用户界面(GUI)环境中,验证码的生成可能与窗口...

    用labview实现的正态分布的随机数并生成对应的直方图

    用labview实现的正态分布的随机数并生成对应的直方图(Achieved with labview normally distributed random numbers and generate the corresponding histogram)

    random-array:用随机数创建数组

    随机数组 生成随机数数组 安装 npm install random-...//Generate array of size 10 and round numbers between 1 and 10 random ( 1 , 10 ) . oned ( 10 , { round : true } ) ; 生成随机数数组,而函数为false。

    随机选号随机种子应用

    std::vector&lt;int&gt; winning_numbers = generate_lotto_numbers(6, 49); // 输出中奖号码 for (int num : winning_numbers) { std::cout ; } return 0; } ``` 这段代码首先创建了一个1到49的整数向量,然后使用...

    产生1到N的不重复随机数

    random.shuffle(numbers) return numbers ``` 上述方法虽然简单,但当N非常大时,创建完整的列表可能会消耗大量内存。为了解决这个问题,可以使用“鱼缸抽样”(也称为“不放回抽样”)算法。这种方法不创建完整...

    集成电路故障模拟器

    FSIM has the ability to generate pseudo-random patterns with various starting seeds and fault-simulate them. You can use this capability to test your own code on pseudo-random numbers, and use it as a...

Global site tag (gtag.js) - Google Analytics