0

I'm converting Matlab program to Python.

I'm trying to random sampling from an array by using np.random.choice, but the result doesn't match with Matlab randsample.

For example,

I did this with Python,

np.random.seed(100)
a = np.arange(10, 110, 10)
np.random.choice(a, 2, True)

>> Output: array([90, 90])

And the following is Matlab,

rng(100)
a = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
randsample(a, 2, true)

>> Output: 60 30

Values in both arrays are different. Am I doing something wrong?

Any help will be appreciated, Thanks!

Inundata
  • 45
  • 3
  • 3
    There's no particular reason to *expect* them to be the same. – user2357112 Apr 15 '21 at 03:24
  • @user2357112supportsMonica I believe they're asking since from what I could find, both of them use the Mersenne twister random number generation algorithm. But there's still any number of things that could cause the different results. – duckboycool Apr 15 '21 at 03:25
  • Have you tried looking at this? https://stackoverflow.com/questions/18486241/comparing-matlab-and-numpy-code-that-uses-random-number-generation try specifying 'twister' in the matlab rng() function – jtsw1990 Apr 15 '21 at 03:30
  • @jtsw1990 I checked that question. But the result is same...Anyway thanks for your help :) – Inundata Apr 15 '21 at 04:06
  • @user2357112supportsMonica I know that the two programs have the same random number generation algorithm, isn't it? If they have the same algorithm, I thought they would return the same result. – Inundata Apr 15 '21 at 04:10
  • 1
    @Inundata: The Mersenne twister is only the central component of an RNG library, like the engine of a car. Just like two cars with the same model of engine can behave entirely differently, two libraries that both have the Mersenne twister at their core can use the raw Mersenne twister output completely differently. – user2357112 Apr 15 '21 at 04:24
  • 4
    And because MATLAB is not open source, we cannot know what they do to randomly select values. The only way to get identical results in both is to write the algorithms yourself. – Cris Luengo Apr 15 '21 at 04:40

0 Answers0