Changeset 26598


Ignore:
Timestamp:
11/10/21 17:43:20 (3 years ago)
Author:
bulthuis
Message:

CHG: a few changes for random generators

Location:
issm/trunk-jpl/src/c/shared/Random
Files:
2 edited

Legend:

Unmodified
Added
Removed
  • issm/trunk-jpl/src/c/shared/Random/randomgenerator.cpp

    r26597 r26598  
    22 * \brief random number generating functions
    33 */
     4
     5#include <iostream>
     6#include "./randomgenerator.h"
     7
     8#undef M_PI
     9#define M_PI 3.141592653589793238462643
  • issm/trunk-jpl/src/c/shared/Random/randomgenerator.h

    r26597 r26598  
    22 * \brief prototypes for randomgenerator.h
    33 */
     4
     5#ifndef _RANDOMGENERATOR_H_
     6#define _RANDOMGENERATOR_H_
     7
     8/*Headers:*/
     9/*{{{*/
     10#include <cmath>
     11/*}}}*/
     12
     13#undef M_PI
     14#define M_PI 3.141592653589793238462643
     15
     16class rnd_uniform_distribution
     17{
     18
     19  private:
     20    int a;
     21    int c;
     22    unsigned int m;
     23    unsigned _seed;
     24    double lbound;
     25    double ubound;
     26
     27  public:
     28
     29    /*constructors, destructors: */
     30    rnd_uniform_distribution() : _seed( 0 ), a( 1103515245 ), c( 12345 ), m( 2147483648 ), lbound(0.0), ubound(1.0) {}
     31    rnd_uniform_distribution(double a_1,double a_2) : _seed( 0 ), a( 1103515245 ), c( 12345 ), m( 2147483648 ), lbound(a_1), ubound(a_2) {}
     32    ~rnd_uniform_distribution(){}
     33
     34    void seed( unsigned int s ) { _seed = s; }
     35    unsigned int get_seed() { return _seed; }
     36    double generator(){
     37      _seed = ( a * _seed + c ) % m;
     38      return (ubound-lbound)*(double) _seed/ m + lbound;
     39    }
     40
     41};
     42
     43class rnd_normal_distribution
     44{
     45
     46  private:
     47    unsigned _seed;
     48    double mean;
     49    double sdev;
     50
     51  public:
     52
     53    /*constructors, destructors: */
     54    rnd_normal_distribution() : _seed( 0 ), mean( 0), sdev(1.0) {}
     55    rnd_normal_distribution(double m,double s) : _seed( 0 ), mean( m ), sdev(s) {}
     56    ~rnd_normal_distribution(){}
     57
     58    void seed( unsigned int s ) { _seed = s; }
     59    double generator()
     60    {
     61      rnd_uniform_distribution unifdistri;
     62      unifdistri.seed(_seed);
     63
     64      double u1 = unifdistri.generator();
     65      double u2 = unifdistri.generator();
     66
     67      double R = sqrt(-2*log(u1));
     68      double theta = 2*M_PI*u2;
     69
     70      seed(unifdistri.get_seed());
     71
     72      return mean + sdev * (R*cos(theta));
     73
     74    }
     75
     76};
     77
     78#endif //ifndef _RANDOMGENERATOR_H_
Note: See TracChangeset for help on using the changeset viewer.