TE
TechEcho
Home24h TopNewestBestAskShowJobs
GitHubTwitter
Home

TechEcho

A tech news platform built with Next.js, providing global tech news and discussions.

GitHubTwitter

Home

HomeNewestBestAskShowJobs

Resources

HackerNews APIOriginal HackerNewsNext.js

© 2025 TechEcho. All rights reserved.

Dissecting Lemire’s nearly divisionless random

13 pointsby bbgmover 4 years ago

1 comment

kwilletsover 4 years ago
Oops, I started on an entry for this, and then went off with some new variants on the algo and forgot my original goal.<p>But I did make it fairly readable:<p><pre><code> FixedPoint&lt;uint32_t&gt; x; do { x.setFraction(src()); x *= range; } while(isRejectedValue(x.fraction())); return x.floor(); </code></pre> Basically all the weird casts and things in Lemire are parts of 32.32 fixed point arithmetic; we stuff a random value into the .32 part to make a number in [0,1) and multiply. The rejection condition is a bit of modular arithmetic but not super hard.<p><a href="https:&#x2F;&#x2F;github.com&#x2F;KWillets&#x2F;range_generator&#x2F;blob&#x2F;59ffea502c4a76ad059ea7b06b29b9d00e0a3e26&#x2F;include&#x2F;range_generator.hpp#L49" rel="nofollow">https:&#x2F;&#x2F;github.com&#x2F;KWillets&#x2F;range_generator&#x2F;blob&#x2F;59ffea502c4...</a><p>I added another method where it doesn&#x27;t reject but extends right (variable-precision) until it&#x27;s certain of the exact answer (ie that the floor() cannot change). I believe the Ryu printf algorithm does something similar to get the requested number of digits. It&#x27;s unbiased but uses more random bits, which are expensive.