Why does the random constructor in C # assign the Seed parameter at the end of the method?

I checked the source code of the Random.Net class here . The last line surprises me

  public Random(int Seed) {
    int ii;
    int mj, mk;

    //Initialize our Seed array.
    //This algorithm comes from Numerical Recipes in C (2nd Ed.)
    int subtraction = (Seed == Int32.MinValue) ? Int32.MaxValue : Math.Abs(Seed);
    mj = MSEED - subtraction;
    SeedArray[55]=mj;
    mk=1;
    for (int i=1; i<55; i++) {  //Apparently the range [1..55] is special (Knuth) and so we're wasting the 0'th position.
      ii = (21*i)%55;
      SeedArray[ii]=mk;
      mk = mj - mk;
      if (mk<0) mk+=MBIG;
      mj=SeedArray[ii];
    }
    for (int k=1; k<5; k++) {
      for (int i=1; i<56; i++) {
    SeedArray[i] -= SeedArray[1+(i+30)%55];
    if (SeedArray[i]<0) SeedArray[i]+=MBIG;
      }
    }
    inext=0;
    inextp = 21;
    Seed = 1;
  }

      

What is the purpose of assigning a parameter at the end of a method?

+3


source to share


3 answers


Since the parameter is Seed

not passed ref

but int

is the value type, then the last line has no effect.

Thanks to @Alex K for pointing this out, after checking the algorithm they adapted to Numericical Recipes in C, they did copy and paste this last line:



if ( * idum < 0 || iff == 0) {
  Initialization.
  iff = 1;
  mj = labs(MSEED - labs( * idum));
  Initialize ma[55] using the seed idum and the
  mj %= MBIG;
  large number MSEED.
  ma[55] = mj;
  mk = 1;
  for (i = 1; i <= 54; i++) {
    ii = (21 * i) % 55;
    ma[ii] = mk;
    mk = mj - mk;
    if (mk < MZ) mk += MBIG;
    mj = ma[ii];
  }
  for (k = 1; k <= 4; k++)
    (i = 1; i <= 55; i++) {
    ator."
    ma[i] -= ma[1 + (i + 30) % 55];
    if (ma[i] < MZ) ma[i] += MBIG;
  }
  inext = 0;
  inextp = 31;
  * idum = 1;
}

      

+5


source


This is an erroneous translation of a function float rand3(long *idum)

from the book Numerical Repetitions in C (2nd Edition) (p. 283). This part is for initializing the seed array ( idum

- seed parameter):

iff=1;
mj=labs(MSEED-labs(*idum)); 
mj %= MBIG; large number MSEED.
ma[55]=mj;
mk=1;
for (i=1;i<=54;i++) { 
    ii=(21*i) % 55;
    ma[ii]=mk; 
    mk=mj-mk;
    if (mk < MZ) mk += MBIG;
        mj=ma[ii];
}
for (k=1;k<=4;k++)
    (i=1;i<=55;i++) { 
        ma[i] -= ma[1+(i+30) % 55];
       if (ma[i] < MZ) ma[i] += MBIG;
    }
inext=0; 
inextp=31;
*idum=1;

      



The translator did not set the seed parameter to ref

. So the line doesn't affect the C # translation.

+2


source


There is Seed

no point in using the setting . It is a variable of type local value with no use after the constructor completes.

I think this is just a mistake.

+1


source







All Articles