weighted_dist_test.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /*
  2. * Copyright (c) 2014, Yawning Angel <yawning at schwanenlied dot me>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * * Redistributions of source code must retain the above copyright notice,
  9. * this list of conditions and the following disclaimer.
  10. *
  11. * * Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  18. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
  19. * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  20. * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  21. * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  22. * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  23. * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  24. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  25. * POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. package probdist
  28. import (
  29. "fmt"
  30. "testing"
  31. "gitlab.torproject.org/tpo/anti-censorship/pluggable-transports/lyrebird/common/drbg"
  32. )
  33. const debug = false
  34. func TestWeightedDist(t *testing.T) {
  35. seed, err := drbg.NewSeed()
  36. if err != nil {
  37. t.Fatal("failed to generate a DRBG seed:", err)
  38. }
  39. const nrTrials = 1000000
  40. hist := make([]int, 1000)
  41. w := New(seed, 0, 999, true)
  42. if debug {
  43. // Dump a string representation of the probability table.
  44. fmt.Println("Table:")
  45. var sum float64
  46. for _, weight := range w.weights {
  47. sum += weight
  48. }
  49. for i, weight := range w.weights {
  50. p := weight / sum
  51. if p > 0.000001 { // Filter out tiny values.
  52. fmt.Printf(" [%d]: %f\n", w.minValue+w.values[i], p)
  53. }
  54. }
  55. fmt.Println()
  56. }
  57. for i := 0; i < nrTrials; i++ {
  58. value := w.Sample()
  59. hist[value]++
  60. }
  61. if debug {
  62. fmt.Println("Generated:")
  63. for value, count := range hist {
  64. if count != 0 {
  65. p := float64(count) / float64(nrTrials)
  66. fmt.Printf(" [%d]: %f (%d)\n", value, p, count)
  67. }
  68. }
  69. }
  70. }