How do I generate random numbers in Dart?

前端 未结 14 1461
一个人的身影
一个人的身影 2021-01-31 06:49

How do I generate random numbers using Dart?

14条回答
  •  半阙折子戏
    2021-01-31 07:26

    Just wrote this little class for generating Normal Random numbers... it was a decent starting point for the checking I need to do. (These sets will distribute on a "bell" shaped curve.) The seed will be set randomly, but if you want to be able to re-generate a set you can just pass some specific seed and the same set will generate.

    Have fun...

    class RandomNormal {
      num     _min, _max,  _sum;
      int     _nEle, _seed, _hLim;
      Random  _random;
      List    _rNAr;
    
      //getter
      List get randomNumberAr => _rNAr;
    
      num _randomN() {
        int r0 = _random.nextInt(_hLim);
        int r1 = _random.nextInt(_hLim);
        int r2 = _random.nextInt(_hLim);
        int r3 = _random.nextInt(_hLim);
    
        num rslt = _min + (r0 + r1 + r2 + r3) / 4000.0;  //Add the OS back in...
        _sum += rslt; //#DEBUG ONLY
        return( rslt );
      }
    
      RandomNormal(this._nEle, this._min, this._max, [this._seed = null]) {
        if (_seed == null ) {
          Random r = new Random();
          _seed    = r.nextInt(1000);
        }
        _hLim   = (_max - _min).ceil() * 1000;
        _random = new Random(_seed);
        _rNAr   = [];
        _sum    = 0;//#DEBUG ONLY
    
        h2("RandomNormal with k: ${_nEle}, Seed: ${_seed}, Min: ${_min}, Max: ${_max}");//#DEBUG ONLY
        for(int n = 0; n < _nEle; n++ ){
          num randomN = _randomN();
          //p("randomN  = ${randomN}");
          LIST_add( _rNAr, randomN );
        }
    
        h3("Mean = ${_sum/_nEle}");//#DEBUG ONLY
      }
    }
    
    
    new RandomNormal(1000, 80, 120);
    new RandomNormal(1000, 80, 120);
    new RandomNormal(1000, 80, 120);
    new RandomNormal(1000, 80, 120);
    new RandomNormal(1000, 80, 120);
    new RandomNormal(1000, 80, 120);
    new RandomNormal(1000, 80, 120);
    

    Then you can just use it like this to check the mean of sets of 1000 nums generated between a low and high limit. The values are stored in the class so they can be accessed after instantiation.

    _swarmii

提交回复
热议问题