gravatar
alpar (Alpar Juttner)
alpar@cs.elte.hu
Serious buxfixes in Random::gamma() and Random::pareto()
0 1 0
default
1 file changed with 2 insertions and 2 deletions:
↑ Collapse diff ↑
Ignore white space 768 line context
... ...
@@ -414,502 +414,502 @@
414 414

	
415 415
      static Result convert(RandomCore<Word>& rnd) {
416 416
        return Shifting<Result, - shift - bits>::
417 417
          shift(static_cast<Result>(rnd())) +
418 418
          RealConversion<Result, Word, rest-bits, shift + bits>::
419 419
          convert(rnd);
420 420
      }
421 421
    };
422 422

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

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

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

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

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

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

	
466 466
  }
467 467

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

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

	
527 527
  public:
528 528

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

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

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

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

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

	
577 577
    /// \brief Seeding random sequence
578 578
    ///
579 579
    /// Seeding the random sequence. The current number type will be
580 580
    /// converted to the architecture word type.
581 581
    template <typename Number>
582 582
    void seed(Number seed) { 
583 583
      _random_bits::Initializer<Number, Word>::init(core, seed);
584 584
    }
585 585

	
586 586
    /// \brief Seeding random sequence
587 587
    ///
588 588
    /// Seeding the random sequence. The given range should contain
589 589
    /// any number type and the numbers will be converted to the
590 590
    /// architecture word type.
591 591
    template <typename Iterator>
592 592
    void seed(Iterator begin, Iterator end) { 
593 593
      typedef typename std::iterator_traits<Iterator>::value_type Number;
594 594
      _random_bits::Initializer<Number, Word>::init(core, begin, end);
595 595
    }
596 596

	
597 597
    /// \brief Returns a random real number from the range [0, 1)
598 598
    ///
599 599
    /// It returns a random real number from the range [0, 1). The
600 600
    /// default Number type is \c double.
601 601
    template <typename Number>
602 602
    Number real() {
603 603
      return _random_bits::RealConversion<Number, Word>::convert(core);
604 604
    }
605 605

	
606 606
    double real() {
607 607
      return real<double>();
608 608
    }
609 609

	
610 610
    /// \brief Returns a random real number the range [0, b)
611 611
    ///
612 612
    /// It returns a random real number from the range [0, b).
613 613
    template <typename Number>
614 614
    Number real(Number b) { 
615 615
      return real<Number>() * b; 
616 616
    }
617 617

	
618 618
    /// \brief Returns a random real number from the range [a, b)
619 619
    ///
620 620
    /// It returns a random real number from the range [a, b).
621 621
    template <typename Number>
622 622
    Number real(Number a, Number b) { 
623 623
      return real<Number>() * (b - a) + a; 
624 624
    }
625 625

	
626 626
    /// \brief Returns a random real number from the range [0, 1)
627 627
    ///
628 628
    /// It returns a random double from the range [0, 1).
629 629
    double operator()() {
630 630
      return real<double>();
631 631
    }
632 632

	
633 633
    /// \brief Returns a random real number from the range [0, b)
634 634
    ///
635 635
    /// It returns a random real number from the range [0, b).
636 636
    template <typename Number>
637 637
    Number operator()(Number b) { 
638 638
      return real<Number>() * b; 
639 639
    }
640 640

	
641 641
    /// \brief Returns a random real number from the range [a, b)
642 642
    ///
643 643
    /// It returns a random real number from the range [a, b).
644 644
    template <typename Number>
645 645
    Number operator()(Number a, Number b) { 
646 646
      return real<Number>() * (b - a) + a; 
647 647
    }
648 648

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

	
657 657
    /// \brief Returns a random integer from a range
658 658
    ///
659 659
    /// It returns a random integer from the range {a, a + 1, ..., b - 1}.
660 660
    template <typename Number>
661 661
    Number integer(Number a, Number b) {
662 662
      return _random_bits::Mapping<Number, Word>::map(core, b - a) + a;
663 663
    }
664 664

	
665 665
    /// \brief Returns a random integer from a range
666 666
    ///
667 667
    /// It returns a random integer from the range {0, 1, ..., b - 1}.
668 668
    template <typename Number>
669 669
    Number operator[](Number b) {
670 670
      return _random_bits::Mapping<Number, Word>::map(core, b);
671 671
    }
672 672

	
673 673
    /// \brief Returns a random non-negative integer
674 674
    ///
675 675
    /// It returns a random non-negative integer uniformly from the
676 676
    /// whole range of the current \c Number type. The default result
677 677
    /// type of this function is <tt>unsigned int</tt>.
678 678
    template <typename Number>
679 679
    Number uinteger() {
680 680
      return _random_bits::IntConversion<Number, Word>::convert(core);
681 681
    }
682 682

	
683 683
    unsigned int uinteger() {
684 684
      return uinteger<unsigned int>();
685 685
    }
686 686

	
687 687
    /// \brief Returns a random integer
688 688
    ///
689 689
    /// It returns a random integer uniformly from the whole range of
690 690
    /// the current \c Number type. The default result type of this
691 691
    /// function is \c int.
692 692
    template <typename Number>
693 693
    Number integer() {
694 694
      static const int nb = std::numeric_limits<Number>::digits + 
695 695
        (std::numeric_limits<Number>::is_signed ? 1 : 0);
696 696
      return _random_bits::IntConversion<Number, Word, nb>::convert(core);
697 697
    }
698 698

	
699 699
    int integer() {
700 700
      return integer<int>();
701 701
    }
702 702
    
703 703
    /// \brief Returns a random bool
704 704
    ///
705 705
    /// It returns a random bool. The generator holds a buffer for
706 706
    /// random bits. Every time when it become empty the generator makes
707 707
    /// a new random word and fill the buffer up.
708 708
    bool boolean() {
709 709
      return bool_producer.convert(core);
710 710
    }
711 711

	
712 712
    ///\name Non-uniform distributions
713 713
    ///
714 714
    
715 715
    ///@{
716 716
    
717 717
    /// \brief Returns a random bool
718 718
    ///
719 719
    /// It returns a random bool with given probability of true result.
720 720
    bool boolean(double p) {
721 721
      return operator()() < p;
722 722
    }
723 723

	
724 724
    /// Standard Gauss distribution
725 725

	
726 726
    /// Standard Gauss distribution.
727 727
    /// \note The Cartesian form of the Box-Muller
728 728
    /// transformation is used to generate a random normal distribution.
729 729
    /// \todo Consider using the "ziggurat" method instead.
730 730
    double gauss() 
731 731
    {
732 732
      double V1,V2,S;
733 733
      do {
734 734
	V1=2*real<double>()-1;
735 735
	V2=2*real<double>()-1;
736 736
	S=V1*V1+V2*V2;
737 737
      } while(S>=1);
738 738
      return std::sqrt(-2*std::log(S)/S)*V1;
739 739
    }
740 740
    /// Gauss distribution with given mean and standard deviation
741 741

	
742 742
    /// Gauss distribution with given mean and standard deviation.
743 743
    /// \sa gauss()
744 744
    double gauss(double mean,double std_dev)
745 745
    {
746 746
      return gauss()*std_dev+mean;
747 747
    }
748 748

	
749 749
    /// Exponential distribution with given mean
750 750

	
751 751
    /// This function generates an exponential distribution random number
752 752
    /// with mean <tt>1/lambda</tt>.
753 753
    ///
754 754
    double exponential(double lambda=1.0)
755 755
    {
756 756
      return -std::log(1.0-real<double>())/lambda;
757 757
    }
758 758

	
759 759
    /// Gamma distribution with given integer shape
760 760

	
761 761
    /// This function generates a gamma distribution random number.
762 762
    /// 
763 763
    ///\param k shape parameter (<tt>k>0</tt> integer)
764 764
    double gamma(int k) 
765 765
    {
766 766
      double s = 0;
767 767
      for(int i=0;i<k;i++) s-=std::log(1.0-real<double>());
768 768
      return s;
769 769
    }
770 770
    
771 771
    /// Gamma distribution with given shape and scale parameter
772 772

	
773 773
    /// This function generates a gamma distribution random number.
774 774
    /// 
775 775
    ///\param k shape parameter (<tt>k>0</tt>)
776 776
    ///\param theta scale parameter
777 777
    ///
778 778
    double gamma(double k,double theta=1.0)
779 779
    {
780 780
      double xi,nu;
781 781
      const double delta = k-std::floor(k);
782 782
      const double v0=E/(E-delta);
783 783
      do {
784 784
	double V0=1.0-real<double>();
785 785
	double V1=1.0-real<double>();
786 786
	double V2=1.0-real<double>();
787 787
	if(V2<=v0) 
788 788
	  {
789 789
	    xi=std::pow(V1,1.0/delta);
790 790
	    nu=V0*std::pow(xi,delta-1.0);
791 791
	  }
792 792
	else 
793 793
	  {
794 794
	    xi=1.0-std::log(V1);
795 795
	    nu=V0*std::exp(-xi);
796 796
	  }
797 797
      } while(nu>std::pow(xi,delta-1.0)*std::exp(-xi));
798
      return theta*(xi-gamma(int(std::floor(k))));
798
      return theta*(xi+gamma(int(std::floor(k))));
799 799
    }
800 800
    
801 801
    /// Weibull distribution
802 802

	
803 803
    /// This function generates a Weibull distribution random number.
804 804
    /// 
805 805
    ///\param k shape parameter (<tt>k>0</tt>)
806 806
    ///\param lambda scale parameter (<tt>lambda>0</tt>)
807 807
    ///
808 808
    double weibull(double k,double lambda)
809 809
    {
810 810
      return lambda*pow(-std::log(1.0-real<double>()),1.0/k);
811 811
    }  
812 812
      
813 813
    /// Pareto distribution
814 814

	
815 815
    /// This function generates a Pareto distribution random number.
816 816
    /// 
817 817
    ///\param k shape parameter (<tt>k>0</tt>)
818 818
    ///\param x_min location parameter (<tt>x_min>0</tt>)
819 819
    ///
820 820
    double pareto(double k,double x_min)
821 821
    {
822
      return exponential(gamma(k,1.0/x_min));
822
      return exponential(gamma(k,1.0/x_min))+x_min;
823 823
    }  
824 824
      
825 825
    /// Poisson distribution
826 826

	
827 827
    /// This function generates a Poisson distribution random number with
828 828
    /// parameter \c lambda.
829 829
    /// 
830 830
    /// The probability mass function of this distribusion is
831 831
    /// \f[ \frac{e^{-\lambda}\lambda^k}{k!} \f]
832 832
    /// \note The algorithm is taken from the book of Donald E. Knuth titled
833 833
    /// ''Seminumerical Algorithms'' (1969). Its running time is linear in the
834 834
    /// return value.
835 835
    
836 836
    int poisson(double lambda)
837 837
    {
838 838
      const double l = std::exp(-lambda);
839 839
      int k=0;
840 840
      double p = 1.0;
841 841
      do {
842 842
	k++;
843 843
	p*=real<double>();
844 844
      } while (p>=l);
845 845
      return k-1;
846 846
    }  
847 847
      
848 848
    ///@}
849 849
    
850 850
    ///\name Two dimensional distributions
851 851
    ///
852 852

	
853 853
    ///@{
854 854
    
855 855
    /// Uniform distribution on the full unit circle
856 856

	
857 857
    /// Uniform distribution on the full unit circle.
858 858
    ///
859 859
    dim2::Point<double> disc() 
860 860
    {
861 861
      double V1,V2;
862 862
      do {
863 863
	V1=2*real<double>()-1;
864 864
	V2=2*real<double>()-1;
865 865
	
866 866
      } while(V1*V1+V2*V2>=1);
867 867
      return dim2::Point<double>(V1,V2);
868 868
    }
869 869
    /// A kind of two dimensional Gauss distribution
870 870

	
871 871
    /// This function provides a turning symmetric two-dimensional distribution.
872 872
    /// Both coordinates are of standard normal distribution, but they are not
873 873
    /// independent.
874 874
    ///
875 875
    /// \note The coordinates are the two random variables provided by
876 876
    /// the Box-Muller method.
877 877
    dim2::Point<double> gauss2()
878 878
    {
879 879
      double V1,V2,S;
880 880
      do {
881 881
	V1=2*real<double>()-1;
882 882
	V2=2*real<double>()-1;
883 883
	S=V1*V1+V2*V2;
884 884
      } while(S>=1);
885 885
      double W=std::sqrt(-2*std::log(S)/S);
886 886
      return dim2::Point<double>(W*V1,W*V2);
887 887
    }
888 888
    /// A kind of two dimensional exponential distribution
889 889

	
890 890
    /// This function provides a turning symmetric two-dimensional distribution.
891 891
    /// The x-coordinate is of conditionally exponential distribution
892 892
    /// with the condition that x is positive and y=0. If x is negative and 
893 893
    /// y=0 then, -x is of exponential distribution. The same is true for the
894 894
    /// y-coordinate.
895 895
    dim2::Point<double> exponential2() 
896 896
    {
897 897
      double V1,V2,S;
898 898
      do {
899 899
	V1=2*real<double>()-1;
900 900
	V2=2*real<double>()-1;
901 901
	S=V1*V1+V2*V2;
902 902
      } while(S>=1);
903 903
      double W=-std::log(S)/S;
904 904
      return dim2::Point<double>(W*V1,W*V2);
905 905
    }
906 906

	
907 907
    ///@}    
908 908
  };
909 909

	
910 910

	
911 911
  extern Random rnd;
912 912

	
913 913
}
914 914

	
915 915
#endif
0 comments (0 inline)