简体   繁体   English

如何生成随机(IEEE-754 单精度)浮点文件?

[英]How do I generate a file of random (IEEE-754 single-precision) floats?

In a bash script, I want to generate a file containing IEEE-754 single-precision floating point values (ie not a text file).在 bash 脚本中,我想生成一个包含 IEEE-754 单精度浮点值的文件(即不是文本文件)。 I want them to have a uniform distribution over some range (which I have as string variables, $min_val and $max_val ; eg -100.0 and 200.0 respectively).我希望它们在某个范围内具有均匀分布(我将其作为字符串变量$min_val$max_val ;例如分别为-100.0200.0 )。 I don't care that much about the "quality" of randomness, so anything passable to the naked human eye will do;我不太关心随机性的“质量”,所以肉眼可以通过的任何东西都可以; and I don't want NaNs or infinities.而且我不想要 NaN 或无穷大。

What's a convenient way to do that?有什么方便的方法来做到这一点? I can't just user random characters from /dev/urandom and such.我不能只使用来自/dev/urandom等的随机字符。

Notes:笔记:

  • You may assume the minimum and maximum and not subnormal.您可以假设最小值和最大值,而不是低于正常值。
  • Other reasonable assumptions can be made, but please make them explicitly.可以做出其他合理的假设,但请明确做出。

My Perl seems to pack floats into the IEEE-754 format.我的 Perl 似乎将浮点数打包成 IEEE-754 格式。

You may need to change this for endian-ness:您可能需要将其更改为字节序:

perl -e '
    ($min,$max,$count) = @ARGV;
    print pack "f*", $min + rand($max-$min) for 1..$count;
' $min $max $count > floatfile

For reference:以供参考:

perl -e 'print pack "f*", Inf, Nan, -118.625, 0.15625' | od -x

gives, on my machine:在我的机器上给出:

0000000 0000 7f80 0000 ffc0 4000 c2ed 0000 3e20
0000020

"f<*" forces little-endian; "f<*"强制小端; "f>*" forces big-endian. "f>*"强制大端。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM