from Hacker News

Evolving the Go Standard Library with math/rand/v2

by spacey on 5/1/24, 3:42 PM with 44 comments

  • by infogulch on 5/2/24, 12:06 AM

    > In 2018, Daniel Lemire found an algorithm that avoids the divisions nearly all the time (see also his 2019 blog post). In math/rand, adopting Lemire’s algorithm would make Intn(1000) 20-30% faster...

    I recently found a super simple algorithm that appears to produce a number in the interval [0,N] with a branchless expression with a single multiplication in an extended number size. (Sorry I don't have a reference.)

    Say you want to generate a number, G, in interval [0,N] where N<=UInt32Max. The algorithm is:

        G = uint32( uint64(N)*uint64(rand.UInt32())>>32 )
    
    It seems like this should select a number in the range with no bias. Is there something I missed?
  • by rollulus on 5/2/24, 7:17 AM

    As often I’m impressed by the quality of all of this. The amount of thinking that went into this, this excellent written blog post. I love the Go blog.
  • by infogulch on 5/2/24, 1:36 AM

    I like the Principles section. Very measured and practical approach to releasing new stdlib packages. https://go.dev/blog/randv2#principles

    The end of the post they mention that an encoding/json/v2 package is in the works: https://github.com/golang/go/discussions/63397

  • by Smaug123 on 5/1/24, 8:55 PM

    Nice - I wish .NET would be more willing to condemn chunks of the standard library and replace them with something better!
  • by skitter on 5/1/24, 11:05 PM

    Related, this article discusses difference generators and tradeoffs for Go using them as Source: https://zephyrtronium.github.io/articles/randomness.html
  • by lifthrasiir on 5/2/24, 5:02 AM

    > Ideally, the v2 package should be able to do everything the v1 package could do, and when v2 is released, the v1 package should be rewritten to be a thin wrapper around v2.

    And even more ideally, as many v1 usages should be automatically fixed as possible by `go fix` or similar tools. Allowing this to all user packages would be a major improvement over the status quo.

  • by 38 on 5/3/24, 11:34 PM

    If both are now crypto secure, what's the point of having both? Also seems like they've made math/rand slower, not a win in my book.