gravatar
alpar (Alpar Juttner)
alpar@cs.elte.hu
Poisson distribution added
0 2 0
default
2 files changed with 24 insertions and 0 deletions:
↑ Collapse diff ↑
Show white space 768 line context
... ...
@@ -422,452 +422,475 @@
422 422
    };
423 423

	
424 424
    template <typename Result, typename Word>
425 425
    struct Initializer {
426 426

	
427 427
      template <typename Iterator>
428 428
      static void init(RandomCore<Word>& rnd, Iterator begin, Iterator end) {
429 429
        std::vector<Word> ws;
430 430
        for (Iterator it = begin; it != end; ++it) {
431 431
          ws.push_back(Word(*it));
432 432
        }
433 433
        rnd.initState(ws.begin(), ws.end());
434 434
      }
435 435

	
436 436
      static void init(RandomCore<Word>& rnd, Result seed) {
437 437
        rnd.initState(seed);
438 438
      }
439 439
    };
440 440

	
441 441
    template <typename Word>
442 442
    struct BoolConversion {
443 443
      static bool convert(RandomCore<Word>& rnd) {
444 444
        return (rnd() & 1) == 1;
445 445
      }
446 446
    };
447 447

	
448 448
    template <typename Word>
449 449
    struct BoolProducer {
450 450
      Word buffer;
451 451
      int num;
452 452
      
453 453
      BoolProducer() : num(0) {}
454 454

	
455 455
      bool convert(RandomCore<Word>& rnd) {
456 456
        if (num == 0) {
457 457
          buffer = rnd();
458 458
          num = RandomTraits<Word>::bits;
459 459
        }
460 460
        bool r = (buffer & 1);
461 461
        buffer >>= 1;
462 462
        --num;
463 463
        return r;
464 464
      }
465 465
    };
466 466

	
467 467
  }
468 468

	
469 469
  /// \ingroup misc
470 470
  ///
471 471
  /// \brief Mersenne Twister random number generator
472 472
  ///
473 473
  /// The Mersenne Twister is a twisted generalized feedback
474 474
  /// shift-register generator of Matsumoto and Nishimura. The period
475 475
  /// of this generator is \f$ 2^{19937} - 1 \f$ and it is
476 476
  /// equi-distributed in 623 dimensions for 32-bit numbers. The time
477 477
  /// performance of this generator is comparable to the commonly used
478 478
  /// generators.
479 479
  ///
480 480
  /// This implementation is specialized for both 32-bit and 64-bit
481 481
  /// architectures. The generators differ sligthly in the
482 482
  /// initialization and generation phase so they produce two
483 483
  /// completly different sequences.
484 484
  ///
485 485
  /// The generator gives back random numbers of serveral types. To
486 486
  /// get a random number from a range of a floating point type you
487 487
  /// can use one form of the \c operator() or the \c real() member
488 488
  /// function. If you want to get random number from the {0, 1, ...,
489 489
  /// n-1} integer range use the \c operator[] or the \c integer()
490 490
  /// method. And to get random number from the whole range of an
491 491
  /// integer type you can use the argumentless \c integer() or \c
492 492
  /// uinteger() functions. After all you can get random bool with
493 493
  /// equal chance of true and false or given probability of true
494 494
  /// result with the \c boolean() member functions.
495 495
  ///
496 496
  ///\code
497 497
  /// // The commented code is identical to the other
498 498
  /// double a = rnd();                     // [0.0, 1.0)
499 499
  /// // double a = rnd.real();             // [0.0, 1.0)
500 500
  /// double b = rnd(100.0);                // [0.0, 100.0)
501 501
  /// // double b = rnd.real(100.0);        // [0.0, 100.0)
502 502
  /// double c = rnd(1.0, 2.0);             // [1.0, 2.0)
503 503
  /// // double c = rnd.real(1.0, 2.0);     // [1.0, 2.0)
504 504
  /// int d = rnd[100000];                  // 0..99999
505 505
  /// // int d = rnd.integer(100000);       // 0..99999
506 506
  /// int e = rnd[6] + 1;                   // 1..6
507 507
  /// // int e = rnd.integer(1, 1 + 6);     // 1..6
508 508
  /// int b = rnd.uinteger<int>();          // 0 .. 2^31 - 1
509 509
  /// int c = rnd.integer<int>();           // - 2^31 .. 2^31 - 1
510 510
  /// bool g = rnd.boolean();               // P(g = true) = 0.5
511 511
  /// bool h = rnd.boolean(0.8);            // P(h = true) = 0.8
512 512
  ///\endcode
513 513
  ///
514 514
  /// LEMON provides a global instance of the random number
515 515
  /// generator which name is \ref lemon::rnd "rnd". Usually it is a
516 516
  /// good programming convenience to use this global generator to get
517 517
  /// random numbers.
518 518
  class Random {
519 519
  private:
520 520

	
521 521
    // Architecture word
522 522
    typedef unsigned long Word;
523 523
    
524 524
    _random_bits::RandomCore<Word> core;
525 525
    _random_bits::BoolProducer<Word> bool_producer;
526 526
    
527 527

	
528 528
  public:
529 529

	
530 530
    /// \brief Default constructor
531 531
    ///
532 532
    /// Constructor with constant seeding.
533 533
    Random() { core.initState(); }
534 534

	
535 535
    /// \brief Constructor with seed
536 536
    ///
537 537
    /// Constructor with seed. The current number type will be converted
538 538
    /// to the architecture word type.
539 539
    template <typename Number>
540 540
    Random(Number seed) { 
541 541
      _random_bits::Initializer<Number, Word>::init(core, seed);
542 542
    }
543 543

	
544 544
    /// \brief Constructor with array seeding
545 545
    ///
546 546
    /// Constructor with array seeding. The given range should contain
547 547
    /// any number type and the numbers will be converted to the
548 548
    /// architecture word type.
549 549
    template <typename Iterator>
550 550
    Random(Iterator begin, Iterator end) { 
551 551
      typedef typename std::iterator_traits<Iterator>::value_type Number;
552 552
      _random_bits::Initializer<Number, Word>::init(core, begin, end);
553 553
    }
554 554

	
555 555
    /// \brief Copy constructor
556 556
    ///
557 557
    /// Copy constructor. The generated sequence will be identical to
558 558
    /// the other sequence. It can be used to save the current state
559 559
    /// of the generator and later use it to generate the same
560 560
    /// sequence.
561 561
    Random(const Random& other) {
562 562
      core.copyState(other.core);
563 563
    }
564 564

	
565 565
    /// \brief Assign operator
566 566
    ///
567 567
    /// Assign operator. The generated sequence will be identical to
568 568
    /// the other sequence. It can be used to save the current state
569 569
    /// of the generator and later use it to generate the same
570 570
    /// sequence.
571 571
    Random& operator=(const Random& other) {
572 572
      if (&other != this) {
573 573
        core.copyState(other.core);
574 574
      }
575 575
      return *this;
576 576
    }
577 577

	
578 578
    /// \brief Returns a random real number from the range [0, 1)
579 579
    ///
580 580
    /// It returns a random real number from the range [0, 1). The
581 581
    /// default Number type is \c double.
582 582
    template <typename Number>
583 583
    Number real() {
584 584
      return _random_bits::RealConversion<Number, Word>::convert(core);
585 585
    }
586 586

	
587 587
    double real() {
588 588
      return real<double>();
589 589
    }
590 590

	
591 591
    /// \brief Returns a random real number the range [0, b)
592 592
    ///
593 593
    /// It returns a random real number from the range [0, b).
594 594
    template <typename Number>
595 595
    Number real(Number b) { 
596 596
      return real<Number>() * b; 
597 597
    }
598 598

	
599 599
    /// \brief Returns a random real number from the range [a, b)
600 600
    ///
601 601
    /// It returns a random real number from the range [a, b).
602 602
    template <typename Number>
603 603
    Number real(Number a, Number b) { 
604 604
      return real<Number>() * (b - a) + a; 
605 605
    }
606 606

	
607 607
    /// \brief Returns a random real number from the range [0, 1)
608 608
    ///
609 609
    /// It returns a random double from the range [0, 1).
610 610
    double operator()() {
611 611
      return real<double>();
612 612
    }
613 613

	
614 614
    /// \brief Returns a random real number from the range [0, b)
615 615
    ///
616 616
    /// It returns a random real number from the range [0, b).
617 617
    template <typename Number>
618 618
    Number operator()(Number b) { 
619 619
      return real<Number>() * b; 
620 620
    }
621 621

	
622 622
    /// \brief Returns a random real number from the range [a, b)
623 623
    ///
624 624
    /// It returns a random real number from the range [a, b).
625 625
    template <typename Number>
626 626
    Number operator()(Number a, Number b) { 
627 627
      return real<Number>() * (b - a) + a; 
628 628
    }
629 629

	
630 630
    /// \brief Returns a random integer from a range
631 631
    ///
632 632
    /// It returns a random integer from the range {0, 1, ..., b - 1}.
633 633
    template <typename Number>
634 634
    Number integer(Number b) {
635 635
      return _random_bits::Mapping<Number, Word>::map(core, b);
636 636
    }
637 637

	
638 638
    /// \brief Returns a random integer from a range
639 639
    ///
640 640
    /// It returns a random integer from the range {a, a + 1, ..., b - 1}.
641 641
    template <typename Number>
642 642
    Number integer(Number a, Number b) {
643 643
      return _random_bits::Mapping<Number, Word>::map(core, b - a) + a;
644 644
    }
645 645

	
646 646
    /// \brief Returns a random integer from a range
647 647
    ///
648 648
    /// It returns a random integer from the range {0, 1, ..., b - 1}.
649 649
    template <typename Number>
650 650
    Number operator[](Number b) {
651 651
      return _random_bits::Mapping<Number, Word>::map(core, b);
652 652
    }
653 653

	
654 654
    /// \brief Returns a random non-negative integer
655 655
    ///
656 656
    /// It returns a random non-negative integer uniformly from the
657 657
    /// whole range of the current \c Number type. The default result
658 658
    /// type of this function is <tt>unsigned int</tt>.
659 659
    template <typename Number>
660 660
    Number uinteger() {
661 661
      return _random_bits::IntConversion<Number, Word>::convert(core);
662 662
    }
663 663

	
664 664
    unsigned int uinteger() {
665 665
      return uinteger<unsigned int>();
666 666
    }
667 667

	
668 668
    /// \brief Returns a random integer
669 669
    ///
670 670
    /// It returns a random integer uniformly from the whole range of
671 671
    /// the current \c Number type. The default result type of this
672 672
    /// function is \c int.
673 673
    template <typename Number>
674 674
    Number integer() {
675 675
      static const int nb = std::numeric_limits<Number>::digits + 
676 676
        (std::numeric_limits<Number>::is_signed ? 1 : 0);
677 677
      return _random_bits::IntConversion<Number, Word, nb>::convert(core);
678 678
    }
679 679

	
680 680
    int integer() {
681 681
      return integer<int>();
682 682
    }
683 683
    
684 684
    /// \brief Returns a random bool
685 685
    ///
686 686
    /// It returns a random bool. The generator holds a buffer for
687 687
    /// random bits. Every time when it become empty the generator makes
688 688
    /// a new random word and fill the buffer up.
689 689
    bool boolean() {
690 690
      return bool_producer.convert(core);
691 691
    }
692 692

	
693 693
    ///\name Non-uniform distributions
694 694
    ///
695 695
    
696 696
    ///@{
697 697
    
698 698
    /// \brief Returns a random bool
699 699
    ///
700 700
    /// It returns a random bool with given probability of true result.
701 701
    bool boolean(double p) {
702 702
      return operator()() < p;
703 703
    }
704 704

	
705 705
    /// Standard Gauss distribution
706 706

	
707 707
    /// Standard Gauss distribution.
708 708
    /// \note The Cartesian form of the Box-Muller
709 709
    /// transformation is used to generate a random normal distribution.
710 710
    /// \todo Consider using the "ziggurat" method instead.
711 711
    double gauss() 
712 712
    {
713 713
      double V1,V2,S;
714 714
      do {
715 715
	V1=2*real<double>()-1;
716 716
	V2=2*real<double>()-1;
717 717
	S=V1*V1+V2*V2;
718 718
      } while(S>=1);
719 719
      return std::sqrt(-2*std::log(S)/S)*V1;
720 720
    }
721 721
    /// Gauss distribution with given mean and standard deviation
722 722

	
723 723
    /// Gauss distribution with given mean and standard deviation.
724 724
    /// \sa gauss()
725 725
    double gauss(double mean,double std_dev)
726 726
    {
727 727
      return gauss()*std_dev+mean;
728 728
    }
729 729

	
730 730
    /// Exponential distribution with given mean
731 731

	
732 732
    /// This function generates an exponential distribution random number
733 733
    /// with mean <tt>1/lambda</tt>.
734 734
    ///
735 735
    double exponential(double lambda=1.0)
736 736
    {
737 737
      return -std::log(1.0-real<double>())/lambda;
738 738
    }
739 739

	
740 740
    /// Gamma distribution with given integer shape
741 741

	
742 742
    /// This function generates a gamma distribution random number.
743 743
    /// 
744 744
    ///\param k shape parameter (<tt>k>0</tt> integer)
745 745
    double gamma(int k) 
746 746
    {
747 747
      double s = 0;
748 748
      for(int i=0;i<k;i++) s-=std::log(1.0-real<double>());
749 749
      return s;
750 750
    }
751 751
    
752 752
    /// Gamma distribution with given shape and scale parameter
753 753

	
754 754
    /// This function generates a gamma distribution random number.
755 755
    /// 
756 756
    ///\param k shape parameter (<tt>k>0</tt>)
757 757
    ///\param theta scale parameter
758 758
    ///
759 759
    double gamma(double k,double theta=1.0)
760 760
    {
761 761
      double xi,nu;
762 762
      const double delta = k-std::floor(k);
763 763
      const double v0=E/(E-delta);
764 764
      do {
765 765
	double V0=1.0-real<double>();
766 766
	double V1=1.0-real<double>();
767 767
	double V2=1.0-real<double>();
768 768
	if(V2<=v0) 
769 769
	  {
770 770
	    xi=std::pow(V1,1.0/delta);
771 771
	    nu=V0*std::pow(xi,delta-1.0);
772 772
	  }
773 773
	else 
774 774
	  {
775 775
	    xi=1.0-std::log(V1);
776 776
	    nu=V0*std::exp(-xi);
777 777
	  }
778 778
      } while(nu>std::pow(xi,delta-1.0)*std::exp(-xi));
779 779
      return theta*(xi-gamma(int(std::floor(k))));
780 780
    }
781 781
    
782 782
    /// Weibull distribution
783 783

	
784 784
    /// This function generates a Weibull distribution random number.
785 785
    /// 
786 786
    ///\param k shape parameter (<tt>k>0</tt>)
787 787
    ///\param lambda scale parameter (<tt>lambda>0</tt>)
788 788
    ///
789 789
    double weibull(double k,double lambda)
790 790
    {
791 791
      return lambda*pow(-std::log(1.0-real<double>()),1.0/k);
792 792
    }  
793 793
      
794 794
    /// Pareto distribution
795 795

	
796 796
    /// This function generates a Pareto distribution random number.
797 797
    /// 
798 798
    ///\param k shape parameter (<tt>k>0</tt>)
799 799
    ///\param x_min location parameter (<tt>x_min>0</tt>)
800 800
    ///
801 801
    double pareto(double k,double x_min)
802 802
    {
803 803
      return exponential(gamma(k,1.0/x_min));
804 804
    }  
805 805
      
806
    /// Poisson distribution
807

	
808
    /// This function generates a Poisson distribution random number with
809
    /// parameter \c lambda.
810
    /// 
811
    /// The probability mass function of this distribusion is
812
    /// \f[ \frac{e^{-\lambda}\lambda^k}{k!} \f]
813
    /// \note The algorithm is taken from the book of Donald E. Knuth titled
814
    /// ''Seminumerical Algorithms'' (1969). Its running time is linear in the
815
    /// return value.
816
    
817
    int poisson(double lambda)
818
    {
819
      const double l = std::exp(-lambda);
820
      int k=0;
821
      double p = 1.0;
822
      do {
823
	k++;
824
	p*=real<double>();
825
      } while (p>=l);
826
      return k-1;
827
    }  
828
      
806 829
    ///@}
807 830
    
808 831
    ///\name Two dimensional distributions
809 832
    ///
810 833

	
811 834
    ///@{
812 835
    
813 836
    /// Uniform distribution on the full unit circle
814 837

	
815 838
    /// Uniform distribution on the full unit circle.
816 839
    ///
817 840
    dim2::Point<double> disc() 
818 841
    {
819 842
      double V1,V2;
820 843
      do {
821 844
	V1=2*real<double>()-1;
822 845
	V2=2*real<double>()-1;
823 846
	
824 847
      } while(V1*V1+V2*V2>=1);
825 848
      return dim2::Point<double>(V1,V2);
826 849
    }
827 850
    /// A kind of two dimensional Gauss distribution
828 851

	
829 852
    /// This function provides a turning symmetric two-dimensional distribution.
830 853
    /// Both coordinates are of standard normal distribution, but they are not
831 854
    /// independent.
832 855
    ///
833 856
    /// \note The coordinates are the two random variables provided by
834 857
    /// the Box-Muller method.
835 858
    dim2::Point<double> gauss2()
836 859
    {
837 860
      double V1,V2,S;
838 861
      do {
839 862
	V1=2*real<double>()-1;
840 863
	V2=2*real<double>()-1;
841 864
	S=V1*V1+V2*V2;
842 865
      } while(S>=1);
843 866
      double W=std::sqrt(-2*std::log(S)/S);
844 867
      return dim2::Point<double>(W*V1,W*V2);
845 868
    }
846 869
    /// A kind of two dimensional exponential distribution
847 870

	
848 871
    /// This function provides a turning symmetric two-dimensional distribution.
849 872
    /// The x-coordinate is of conditionally exponential distribution
850 873
    /// with the condition that x is positive and y=0. If x is negative and 
851 874
    /// y=0 then, -x is of exponential distribution. The same is true for the
852 875
    /// y-coordinate.
853 876
    dim2::Point<double> exponential2() 
854 877
    {
855 878
      double V1,V2,S;
856 879
      do {
857 880
	V1=2*real<double>()-1;
858 881
	V2=2*real<double>()-1;
859 882
	S=V1*V1+V2*V2;
860 883
      } while(S>=1);
861 884
      double W=-std::log(S)/S;
862 885
      return dim2::Point<double>(W*V1,W*V2);
863 886
    }
864 887

	
865 888
    ///@}    
866 889
  };
867 890

	
868 891

	
869 892
  extern Random rnd;
870 893

	
871 894
}
872 895

	
873 896
#endif
Show white space 768 line context
1 1
/* -*- C++ -*-
2 2
 *
3 3
 * This file is a part of LEMON, a generic C++ optimization library
4 4
 *
5 5
 * Copyright (C) 2003-2008
6 6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
8 8
 *
9 9
 * Permission to use, modify and distribute this software is granted
10 10
 * provided that this copyright notice appears in all copies. For
11 11
 * precise terms see the accompanying LICENSE file.
12 12
 *
13 13
 * This software is provided "AS IS" with no warranty of any kind,
14 14
 * express or implied, and with no claim as to its suitability for any
15 15
 * purpose.
16 16
 *
17 17
 */
18 18

	
19 19
#include <lemon/random.h>
20 20
#include "test_tools.h"
21 21

	
22 22
///\file \brief Test cases for random.h
23 23
///
24 24
///\todo To be extended
25 25
///
26 26

	
27 27
int main()
28 28
{
29 29
  double a=lemon::rnd();
30 30
  check(a<1.0&&a>0.0,"This should be in [0,1)");
31 31
  a=lemon::rnd.gauss();
32 32
  a=lemon::rnd.gamma(3.45,0);
33 33
  a=lemon::rnd.gamma(4);
34 34
  //Does gamma work with integer k?
35 35
  a=lemon::rnd.gamma(4.0,0);
36
  a=lemon::rnd.poisson(.5);
36 37
}
0 comments (0 inline)