C 随机数生成(纯 C 代码,无库或函数) [英] C Random Number Generation (pure C code, no libraries or functions)

查看:77
本文介绍了C 随机数生成(纯 C 代码,无库或函数)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在 C 中生成一些随机数来测试和调试系统.该系统是一个自定义硬件 (SoC),功能有限,因此我只能使用基本的数学运算.

I need to generate some random numbers in C for testing and debugging the system. The system is a custom hardware (SoC) with a limited set of functions so I can only use basic mathematical operations.

不,我不能在 stdlib 或 math.h 中使用随机数生成器.我需要自己写.那么有没有什么生成随机数的算法?

And no, I can't use random number generators in stdlib or math.h. I need to write it myself. So is there some sort of algorithm for generating random numbers?

我知道一个简单的解决方案是在我的工作站上生成数字并将它们嵌入到模块中,但我不想这样做.

I know that a simple solution is to generate the numbers here on my workstation and embed them into the module, but I don't want to do that.

推荐答案

随机数生成器基本上是一个特殊的*哈希函数,它从起始种子递归运行.

A random number generator is basically a special* hash function which runs recursively from a starting seed.

我在 C# 代码中使用了 MurmurHash2 算法,效果很好.它实施起来非常快速和简单,并且已经过测试,可以很好地分布,并且冲突率很低.该项目有几个不同的开源哈希函数,用 C++ 编写,应该很容易转换为 C.

I've used the MurmurHash2 algorithm in my C# code to good effect. It's extremely fast and simple to implement and has been tested to be very well distributed with low collision rates. The project has several different open source hash functions written in C++ which should be easily convertible to C.

* 特别是我的意思是对一个值运行散列函数应该返回另一个看似随机(但确定)的值,因此输出似乎不会形成模式.另外,返回值的分布应该是均匀分布的.

这篇关于C 随机数生成(纯 C 代码,无库或函数)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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