[DGD] Damage Weapons and Stuff (Math and Code)

Ben Chambers bjchamb at bellsouth.net
Tue Jun 3 05:24:23 CEST 2003


In C++ it is the difference between
0.0004490000449000044900004490000449 milliseconds for the sin/cos version
and
0.0004699000469900046990004699000469 for the other version...  That's the
mean of 9999999 runs, so it should be rather accurate.  How badly would it
slow down in DGD?  Would one version slow down more than the other?  Which
one?  Would it pay to modify the C++ code for DGD to make this a built in
command?

Code for the two version is below:

/* this one is the slower one */
float RandGen::randGaussian()
{
 randomize();
 if (m_bSecVal)
 {
  m_bSecVal = false;
  return m_fSecVal;
 }

 float x1, x2, w, y1, y2;

 do
 {
  x1 = 2.0 * randFloat() - 1.0;
  x2 = 2.0 * randFloat() - 1.0;
  w = x1 * x1 + x2 * x2;
 } while ( w >= 1.0 );

 w = sqrt( (-2.0 * log( w ) ) / w ); /* log = NATURAL logarithm */
 y1 = x1 * w;
 y2 = x2 * w;

 m_bSecVal = true;
 m_fSecVal = y2;
 return y1;
}

/* this one is SLIGHTLY faster, but depending on the implementation of
sin/cos may be slower */
float RandGen::randGaussian2()
{
 if (m_bSecVal)
 {
  m_bSecVal = false;
  return m_fSecVal;
 }

 float mag, phase, y1, y2;

 mag = sqrt (-2.0 * log (randFloat() + 1E-9));
 phase = 2.0 * 3.1415927654 * randFloat();

 y1 = mag * cos (phase);
 y2 = mag * sin (phase);

 m_bSecVal = true;
 m_fSecVal = y2;
 return y1;

}

The trade off is that there is a 75% chance that the first one will only run
the loop once.  There is a 18.75% it will run twice.  There is a 6.25%
chance it will run three times or more.  This is offset by the fact that the
lookup tables for sin/cos/log will only be hit once.  The other version hits
them 3 times (one ln, one cos and one sin).  The question is how efficiently
are the cos + sin implemented vs. how efficiently the random generator can
be implemented... anyone know how these two perform?

_________________________________________________________________
List config page:  http://list.imaginary.com/mailman/listinfo/dgd



More information about the DGD mailing list