iOS 上的高精度随机数

发布于 2024-12-24 18:17:50 字数 496 浏览 1 评论 0原文

我已经尝试了一段时间,但到目前为止还没有任何运气。

在 iOS 上检索两个非常精确的数字之间的随机数的最简单方法是什么?

例如,我想要一个介于 41.37783830549337 和 41.377730629131634 之间的随机数,我该如何实现呢?

提前非常感谢!

编辑:我尝试了这个:

double min = 41.37783830549337;
double max = 41.377730629131634;
double test = ((double)rand() / RAND_MAX) * (max - min) + min;
NSLog(@"Min:%lf, max:%lf, result:%lf",min,max,test);

但结果并不像我希望的那么精确,结果是这样的::

Min:41.377838, max:41.377731, result:41.377838

I have been trying this for a while but thus far haven't had any luck.

What is the easiest way to retrieve a random number between two very precise numbers on iOS?

For example, I want a random number between 41.37783830549337 and 41.377730629131634, how would I accomplish this?

Thank you so much in advance!

Edit: I tried this:

double min = 41.37783830549337;
double max = 41.377730629131634;
double test = ((double)rand() / RAND_MAX) * (max - min) + min;
NSLog(@"Min:%lf, max:%lf, result:%lf",min,max,test);

But the results weren't quite as precise as I was hoping, and ended up like this::

Min:41.377838, max:41.377731, result:41.377838

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

心如荒岛 2024-12-31 18:17:50

您可以将 rand 的输出标准化为您想要的任何范围:

((double)rand() / RAND_MAX) * (max - min) + min

[注意:这是纯 C,我假设它在 Obj-C 中等效工作。]

[< em>注释 2:将 double 替换为您选择的适当数据类型。]

[注释 3:将 rand 替换为 random-您根据情况选择号码来源。]

You can normalise the output of rand to any range you want:

((double)rand() / RAND_MAX) * (max - min) + min

[Note: This is pure C, I'm assuming it works equivalently in Obj-C.]

[Note 2: Replace double with the data-type of your choice as appropriate.]

[Note 3: Replace rand with the random-number source of your choice as appropriate.]

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文