DEV Community

海前 王
海前 王

Posted on

随机分布与随机函数

// ConsoleApplication2.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include <iostream>
#include <random>

void uniform_int_distribution_example() {
    std::default_random_engine dre(std::random_device{}()); // 使用随机设备作为种子
    std::uniform_int_distribution<int> uid(10, 1000); // 定义均匀整数分布范围 [10, 1000]

    std::cout << "Uniform integer distribution:" << std::endl;
    for (int i = 0; i < 10; ++i) {
        int random_number = uid(dre);
        std::cout << random_number << std::endl;
    }
}

void uniform_real_distribution_example() {
    std::default_random_engine dre(std::random_device{}()); // 使用随机设备作为种子
    std::uniform_real_distribution<double> urd(0.0, 1.0); // 定义均匀实数分布范围 [0.0, 1.0]

    std::cout << "Uniform real distribution:" << std::endl;
    for (int i = 0; i < 10; ++i) {
        double random_number = urd(dre);
        std::cout << random_number << std::endl;
    }
}

void normal_distribution_example() {
    std::default_random_engine dre(std::random_device{}()); // 使用随机设备作为种子
    std::normal_distribution<double> nd(0.0, 1.0); // 定义正态分布,均值为 0,标准差为 1

    std::cout << "Normal distribution:" << std::endl;
    for (int i = 0; i < 10; ++i) {
        double random_number = nd(dre);
        std::cout << random_number << std::endl;
    }
}

void bernoulli_distribution_example() {
    std::default_random_engine dre(std::random_device{}()); // 使用随机设备作为种子
    std::bernoulli_distribution bd(0.5); // 定义伯努利分布,成功概率为 0.5

    std::cout << "Bernoulli distribution:" << std::endl;
    for (int i = 0; i < 10; ++i) {
        bool random_boolean = bd(dre);
        std::cout << (random_boolean ? "1" : "0") << std::endl;
    }
}

void poisson_distribution_example() {
    std::default_random_engine dre(std::random_device{}()); // 使用随机设备作为种子
    std::poisson_distribution<int> pd(5.0); // 定义泊松分布,均值(lambda)为 5.0

    std::cout << "Poisson distribution:" << std::endl;
    for (int i = 0; i < 10; ++i) {
        int random_number = pd(dre);
        std::cout << random_number << std::endl;
    }
}

int main() {
    uniform_int_distribution_example();
    uniform_real_distribution_example();
    normal_distribution_example();
    bernoulli_distribution_example();
    poisson_distribution_example();
    return 0;
}
···
Enter fullscreen mode Exit fullscreen mode

Image description

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay