gpt4 book ai didi

math - 如何在 Dart 中创建一个随机的 256 位整数?

转载 作者:行者123 更新时间:2023-12-04 17:23:22 24 4
gpt4 key购买 nike

我想在 Dart 中创建一个随机(均匀分布)256 位整数。
Dart 的 Random 只支持 32 位整数。有任何想法吗?

最佳答案

import "dart:math";

// 16bit, because random.nextInt() only supports (2^32)-1 possible values.
const PARTS = 16; // 256bit / 16bit

void main() {
Random rand = new Random();
int combinedVal = 0;
// random parts
for(var i=0;i<PARTS;i++) {
int part = rand.nextInt(1<<16); // 2^16
print("Part $i: $part");
// shift the 16bit blocks to the left and append the new block
combinedVal <<= 16;
combinedVal += part;
print("Combined: $combinedVal");
}
print("Final Result: $combinedVal");
}

输出(控制台应用程序):
Part 0: 4273569419
Combined: 4273569419
Part 1: 2298770505
Combined: 18354840894089491529
Part 2: 1076269765
Combined: 78833441363397765815400305349
Part 3: 500743884
Combined: 338587052486927055616611084622869610188
Part 4: 1660193956
Combined: 1454220317280387171410917722806313469431388605604
Part 5: 1335995533
Combined: 6245828703898006563427837796799909693532109776937558322317
Part 6: 2409230726
Combined: 26825630019660005909515912993248305589473794217828668028446551175558
Part 7: 3743170719
...

编辑

正如 Darshan Computing 在评论中指出的那样,要使用 dart2js 进行这项工作,需要进行一些修改,这会导致精度损失。要在浏览器、外部库和 js interop 中使用它将需要。例如,我使用了 Leemon Baird 的 public domain BigInt library

HTML文件:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Web Playground</title>
<link rel="stylesheet" href="web_playground.css">
<script src="BigInt.js"></script> <!-- this is the important part -->
</head>
<body>
<h1>Web Playground</h1>
<script type="application/dart" src="web_playground.dart"></script>
<script src="packages/browser/dart.js"></script>
</body>
</html>

Dart 文件:

import "dart:html";
import "package:js/js.dart" as js;

void main() {
var rand = js.context.randBigInt(256,0);
window.alert(js.context.bigInt2str(rand,10));
}

关于math - 如何在 Dart 中创建一个随机的 256 位整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16231567/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com