How can I generate a random number within a range in Rust?

廉价感情. 提交于 2019-12-04 22:44:15
huon

Editor's note: This answer is for a version of Rust prior to 1.0 and is not valid in Rust 1.0.

This has been changing a lot recently (sorry! it's all been me), and in Rust 0.8 it was called gen_integer_range (note the /0.8/ rather than /master/ in the URL, if you are using 0.8 you need to be reading those docs).

A word of warning: .gen_integer_range was entirely incorrect in many ways, the new .gen_range doesn't have incorrectness problems.


Code for master (where .gen_range works fine):

use std::rand::{task_rng, Rng};

fn main() {
    // a number from [-40.0, 13000.0)
    let num: f64 = task_rng().gen_range(-40.0, 1.3e4);
    println!("{}", num);
}
Manoel Stilpen

This generates a random number between 0 and 100 using Rng::gen_range:

extern crate rand; // 0.6.5

use rand::Rng;

fn main() {
    // Generate random number in the range [0, 99]
    let num = rand::thread_rng().gen_range(0, 100);
    println!("{}", num);
}

Don't forget to add the rand dependency to Cargo.toml:

[dependencies]
rand = "0.6.5"
andy boot

The documentation for Rng::gen_range states:

This function is optimised for the case that only a single sample is made from the given range. See also the Uniform distribution type which may be faster if sampling from the same range repeatedly.

Uniform can be used to generate a single value:

use rand::distributions::{Distribution, Uniform}; // 0.6.5

fn main() {
    let step = Uniform::new(0, 50);
    let mut rng = rand::thread_rng();
    let choice = step.sample(&mut rng);
    println!("{}", choice);
}

Playground

Or to generate an iterator of values:

use rand::distributions::{Distribution, Uniform}; // 0.6.5

fn main() {
    let step = Uniform::new(0, 50);
    let mut rng = rand::thread_rng();
    let choices: Vec<_> = step.sample_iter(&mut rng).take(10).collect();
    println!("{:?}", choices);
}

Playground

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!