breeze.stats.distributions.RandBasis.uniform and randLong

38 views
Skip to first unread message

Sanzo Miyazawa

unread,
Dec 1, 2021, 2:58:48 AM12/1/21
to Scala Breeze
The comments of breeze.stats.distributions.RandBasis.uniform indicate
"Uniformly samples in [0,1]". However, I think that this comment should be corrected
as "[0, 1)",  because the java code finally called,
org.apache.commons.math3.random.MersenneTwister.nextDouble
== org.apache.commons.math3.random.BitsStreamGenerator.nextDouble ,
will generate [0, 1).

    public double nextDouble() {
        final long high = ((long) next(26)) << 26;
        final int  low  = next(26);
        return (high | low) * 0x1.0p-52d;
    }

If so,   "require( low <= high)" in the breeze.stats.distributions.Uniform(low, high)
should be "require( low < high)".


Also,  I think that the following codes for randLong are not correct.
 /**
   * Uniformly samples a long integer in [0,n)
   */
  def randLong(n: Long): Rand[Long] = new Rand[Long] {
    def draw() = {
      val value = generator.nextLong & Long.MaxValue
      value % n
    }
  }

 /**
   * Uniformly samples a long integer in [n,m)
   */
  def randLong(n: Long, m: Long): Rand[Long] = new Rand[Long] {
    def draw() = {
      val value = generator.nextLong & Long.MaxValue
      value % (m - n) + n
    }
  }

They may be written as
 /**
   * Uniformly samples a long integer in [0,n)
   */
  def randLong(n: Long): Rand[Long] = new Rand[Long] {
    require(n > 0, "n > 0")
    def draw() = {
      val maxVal = Long.MaxValue - (Long.MaxValue % n) - 1
      var value = (generator.nextLong() & Long.MaxValue)
      while ( value > maxVal ) {
        value = (generator.nextLong() & Long.MaxValue)
      }
      value % n
    }
  }

//Otherwise, simply,

  def randLong(n: Long): Rand[Long] = new Rand[Long] {
    def draw() = generator.nextLong(n)
  }

 /**
   * Uniformly samples a long integer in [n,m)
   */
  def randLong(n: Long, m: Long): Rand[Long] = new Rand[Long] {
    def draw() = randLong(m - n).draw() + n
  }


David Hall

unread,
Dec 1, 2021, 3:00:07 AM12/1/21
to scala-...@googlegroups.com
Yeah fair enough. Could you open issues on the github? github.com/scalanlp/breeze/issues

Thanks!

-- David

--
You received this message because you are subscribed to the Google Groups "Scala Breeze" group.
To unsubscribe from this group and stop receiving emails from it, send an email to scala-breeze...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/scala-breeze/7706cf88-c296-436e-a9be-156581140482n%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages