Random number generator (device): Difference between revisions

jq
(→‎{{header|Kotlin}}: Updated example see https://github.com/dkandalov/rosettacode-kotlin for details)
(jq)
Line 372:
}</lang>
 
=={{header|jq}}==
jq does not provide direct access to /dev/urandom, so in the following we assume the availability of `od`, `tr`, and `fold`, and illustrate how to produce an indefinitely long stream of pseudo-random numbers that are approximately uniformly distributed in the range [0,1].
 
Assuming the jq program shown below is in a file named uniform.jq, the command-line invocation would be:
<pre>od -t x -An /dev/urandom | tr -d " " | fold -w 8 | jq -R -f uniform.jq</pre>
 
<lang jq># allow both upper and lower-case characters
def hex2integer:
explode
| reverse
| map(if . > 96 then . - 87 elif . > 64 then . - 55 else . - 48 end)
| reduce .[] as $c
# state: [power, ans]
([1,0]; (.[0] * 16) as $b | [$b, .[1] + (.[0] * $c)])
| .[1];
 
select(length>0) | hex2integer / pow(16;length)</lang>
 
Notice that the program automatically adjusts the precision based on the length of the hexadecimal numbers presented. Since jq uses IEEE 754 64-bit arithmetic, specifying a larger value to `fold`, such as 10, will produce more precise results.
=={{header|Julia}}==
{{works with|Linux}}
2,461

edits