Search code examples
functionrandomlogarithm

Remapping Random Float value to logarithmic scale


I have a Random float that gives me a value between 0 and 1. I now want to remap that value so that 50% of the time the result is 0.01, 25% of the time it't 0.02, 12.5% of the time it's 0.04....

Somewhat like this:

  • 50% = 0.01
  • 25% = 0.02
  • 12.5% = 0.04
  • 6.25% = 0.08
  • 3.125% = 0.16
  • 1.5625% = 0.32
  • 0.78125% = 0.64

Or with other words remapping 0.0 - 0.5 to 0.00 - 0.01 and 0.50 - 0.75 to 0.01 - 0.02...

I think I can do that with a logarithmic function but I can't figure out how.


Solution

  • Given x, a number in the interval (0, 1), the formula you want is 2^floor(-ln(x)/ln(2)) * 0.01.

    • t = -ln(x)/ln(2) - Negative base-2 logarithm of x.
    • u = 2^floor( t ) - Round t and raise 2 to it.
    • u * 0.01 - Multiply by 0.01.

    Example in Python:

    import math
    arr=[2**int(  (-math.log(random.random())) / math.log(2) ) * 0.01 for i in range(1000)]
    print(arr)
    print(sum(1 if u==0.01 else 0 for u in arr)/len(arr))
    

    There is another way to proceed. Let x be your number again.

    base=0.01
    v=x # Original number
    if base!=0:
       while v<0.5:
          base*=2
          v*=2
    print(base) # Mapped number