Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate random 128 bit decimal in given range in go

Tags:

random

go

Let's say that we have a random number generator that can generate random 32 or 64 bit integers (like rand.Rand in the standard library)

Generating a random int64 in a given range [a,b] is fairly easy:

rand.Seed(time.Now().UnixNano())
n := rand.Int63n(b-a) + a

Is it possible to generate random 128 bit decimal (as defined in specification IEEE 754-2008) in a given range from a combination of 32 or 64 bit random integers?

like image 612
felix Avatar asked Feb 09 '20 00:02

felix


1 Answers

It is possible, but the solution is far from trivial. For a correct solution, there are several things to consider.

For one thing, values with exponent E are 10 times more likely than values with exponent E - 1.

Other issues include subnormal numbers and ranges that straddle zero.

I am aware of the Rademacher Floating-Point Library, which tackled this problem for binary floating-point numbers, but the solution there is complicated and its author has not yet written up how his algorithm works.

EDIT (May 11):

I have now specified an algorithm for generating random "uniform" floating-point numbers—

  • In any range,
  • with full coverage, and
  • regardless of the digit base (such as binary or decimal).
like image 139
Peter O. Avatar answered Oct 04 '22 01:10

Peter O.