Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

1st call to rand(1.0) generates predictable values < 1e-4 for seeds in 0..<26844, unlike C++, python, D, ... #435

Closed
timotheecour opened this issue Dec 8, 2020 · 1 comment

Comments

@timotheecour
Copy link
Owner

timotheecour commented Dec 8, 2020

import std/random

proc main()=
  let n = 100_000
  for i in 1..<n:
    randomize(i)
    let x = rand(1.0)
    doAssert x < 1e-4, $(x, i) # passes for i in 0..<26844
main()

EDIT: very related to this: nim-lang#8589

IMO, still a bug, other languages don't have this issue:

nim: fails

python: works

import random
for i in range(0,10):
  random.seed(a=i)
  print(random.random())

prints:

0.8444218515250481
0.13436424411240122
0.9560342718892494
0.23796462709189137
0.23604808973743452
0.6229016948897019
0.793340083761663
0.32383276483316237
0.2267058593810488
0.46300735781502145

D: works

import std.random,std.conv,std.stdio;
void main(){
  //auto seed = Clock.currTime().toUnixTime;
  for(int i=0;i<10;i++) {
    auto rnd = Random(i.to!int);
    uniform(0.0, 1.0, rnd).writeln;
  }
}

prints:

0.548814
0.417022
0.435995
0.550798
0.96703
0.221993
0.89286
0.0763083
0.873429
0.0103742

C++ works

#include <random>
#include <iostream>

void fn2() {
  // std::random_device rd;
  std::uniform_real_distribution<double> dist(0.0, 1.0);
  for (int i=0; i<10; ++i){
    std::mt19937 mt(i);
    std::cout << dist(mt) << "\n";
  }
}

int main() {
  // fn1();
  fn2();
  return 0;
}

prints:

0.592845
0.997185
0.185082
0.0707249
0.900621
0.0551801
0.947476
0.227339
0.0111144
0.364461

links

https://stackoverflow.com/questions/19665818/generate-random-numbers-using-c11-random-library
https://channel9.msdn.com/Events/GoingNative/2013/rand-Considered-Harmful

@timotheecour timotheecour changed the title 1st call to rand(1.0) generates predictable values < 1e-4 for seeds in 0..<26844 1st call to rand(1.0) generates predictable values < 1e-4 for seeds in 0..<26844, unlike C++, python, D, ... Dec 8, 2020
@timotheecour
Copy link
Owner Author

=> nim-lang#17467

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant