生成浮点随机值(也为负) [英] Generate Float Random Values (also negative)

查看:50
本文介绍了生成浮点随机值(也为负)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 C 中生成浮点随机值?(也否定)

How can i generate float random values in C? (also negative)

推荐答案

一般来说,要从任意分布生成随机数,您首先要生成均匀随机数,然后将它们传递给累积分布函数的逆函数.

In general to generate random numbers from an arbitrary distribution you'd first generate uniform random numbers and then pass them to the inverse of the cumulative distribution function.

>

例如,假设您想要在区间 [-10.0, 10.0] 上均匀分布的随机数,而您所得到的只是来自 [0.0, 1.0] 的随机数.[-10.0, 10.0]上均匀分布的累积分布函数为:

Assume for example that you want random numbers with uniform distribution on the interval [-10.0, 10.0] and all you've got is random numbers from [0.0, 1.0]. Cumulative distribution function of the uniform distribution on [-10.0, 10.0] is:

cdf(x) = 0.05 * x + 0.5   for x in [-10.0, 10.0]

这表示生成的随机数小于 x 的概率.逆是

This expresses the probability that a random number generated is smaller than x. The inverse is

icdf(y) = 20.0 * y - 10.0   for y in [0.0, 1.0]

(您可以通过切换 x 和 y 轴在纸上轻松获得).

(You can obtain this easily on paper by switching the x and y axis).

因此要获得均匀分布在 [-10.0, 10.0] 上的随机数,您可以使用以下代码:

Hence to obtain random numbers uniformly distributed on [-10.0, 10.0] you can use the following code:

#include <stdlib.h>

// Returns uniformly distributed random numbers from [0.0, 1.0].
double uniform0to1Random() {
    double r = random();
    return r / ((double)RAND_MAX + 1);
}

// Returns uniformly distributed random numbers from [-10.0, 10.0].
double myRandom() {
  return 20.0 * uniform0to1Random() - 10.0;
}

事实上,你不需要uniform0to1Random(),因为已经有很多来自[0.0, 1.0]的好的均匀随机数生成器(例如在boost库中).

In fact, you don't need uniform0to1Random() since there are already a lot of good uniform random numbers generators from [0.0, 1.0] (e.g. in the boost library).

通过对逆累积分布进行采样,您可以使用该方法生成具有您想要的几乎任何概率分布的随机数,如上所示.

You can use the method to generate random numbers with nearly any probability distribution you want by sampling the inverse cumulative distribution as shown above.

有关详细信息,请参阅http://en.wikipedia.org/wiki/Inverse_transform_sampling.

See http://en.wikipedia.org/wiki/Inverse_transform_sampling for more details.

这篇关于生成浮点随机值(也为负)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆