如何使用rand()创建随机双精度?(How do I create a random double with rand()?)

编程入门 行业动态 更新时间:2024-10-28 18:23:33
如何使用rand()创建随机双精度?(How do I create a random double with rand()?)

为了生成随机双打,有drand48,但是

这些函数被SVID 3声明为废弃,它声明应该使用rand(3)。

如何用drand48构造我的随机双精度? 在旁注,随机浮动?

简单地从rand()和连接中连接两个int可能会导致NaN ,这是不可接受的。 我想避免仅使用32个随机位进行双精度。

For generating random doubles, there is drand48, but

These functions are declared obsolete by SVID 3, which states that rand(3) should be used instead.

How do I construct my random double with drand48? On a side note, the random float?

Simply concatenating two int from rand() and casting may lead to NaN, which is not acceptable. I'd like to avoid using only 32 random bits for a double.

最满意答案

在linux的手册页中引用一个过时的标准是不幸的。 如果我看到正确的SVID 3是1986年出版的,并且已经过时了。 POSIX具有这一系列功能,并没有计划逐步淘汰它们。

但如果你在这,请考虑使用erand48而不是drand48 。 它的优势在于您自己为它提供种子状态。 通过它是可重入的,如果你在线程环境中使用它(并且以不同方式初始化线程的种子)通常表现得更好,或者如果你需要它用于可重复的模拟则是确定性的。

唯一的小问题是你必须要记住的是它只能给你48位的伪随机性。 通常的double算术是52位,所以要小心你不要使用最低的4位,它们并不好。

This citation of an obsolete standard in the man pages for linux is unfortunate. If I see correctly SVID 3 was published 1986, and obsoleted itself since long. POSIX has this family of functions and there are no plans to phase them out.

But if you are at it, consider to use erand48 instead of drand48. It has the advantage that you provide it with a seed state yourself. By that it is reentrant, generally behaves better if you use it in a threaded environment (and initialize the seeds for threads differently) or is deterministic if you need it for reproducible simulations.

The only little thing is that you have to have in mind is that it only gives you 48 bits of pseudo-randomness. Usual double arithmetic is with 52 bit, so be careful that you don't use the lowest 4 bits, they are no good.

更多推荐

本文发布于:2023-04-27 15:57:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1327346.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   精度   rand   double   create

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!