OiO.lk Community platform!

Oio.lk is an excellent forum for developers, providing a wide range of resources, discussions, and support for those in the developer community. Join oio.lk today to connect with like-minded professionals, share insights, and stay updated on the latest trends and technologies in the development field.
  You need to log in or register to access the solved answers to this problem.
  • You have reached the maximum number of guest views allowed
  • Please register below to remove this limitation

Can I implement `random.randint()` using `random.random()`?

  • Thread starter Thread starter watashiSHUN
  • Start date Start date
W

watashiSHUN

Guest
I want generate a random number between [a,b] inclusive in python

I should be using random.randint(a,b) but what if I only remembered random.random(), which returns a random float [0,1), can I still get an uniform distribution of random numbers?

my thoughts are

  1. round(a + random.random()*(b-a)) I did some test with this...result looks correct, but I am not confident that this is mathematically/statistically correct
  2. take the last few bits, something like random.random() & 0b1111(since the resulting float is supposed to be random set of bits, I am taking a page from here)...but I didn't find a way to convert float to binary or do any bit manipulation on it in python
<p>I want generate a random number between [a,b] inclusive in python</p>
<p>I should be using <code>random.randint(a,b)</code> but what if I only remembered <code>random.random()</code>, which returns a random float [0,1), can I still get an uniform distribution of random numbers?</p>
<p>my thoughts are</p>
<ol>
<li><code>round(a + random.random()*(b-a))</code> I did some test with this...result looks correct, but I am not confident that this is mathematically/statistically correct</li>
<li>take the last few bits, something like <code>random.random() & 0b1111</code>(since the resulting float is supposed to be random set of bits, I am taking a page from <a href="https://github.com/python/cpython/blob/96ead91f0f0db59a942b8b34da9cc980c05588a2/Lib/random.py#L245" rel="nofollow noreferrer">here</a>)...but I didn't find a way to convert float to binary or do any bit manipulation on it in python</li>
</ol>
 

Latest posts

Top