No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.
 
 
 

95 líneas
2.0 KiB

  1. // Copyright 2017 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package distribution
  15. import (
  16. "sync"
  17. "testing"
  18. )
  19. func TestDistribution(t *testing.T) {
  20. // These tests come from examples in https://en.wikipedia.org/wiki/Percentile#The_nearest-rank_method
  21. tests := []struct {
  22. // values in distribution
  23. vals []int
  24. // percentiles and expected percentile values
  25. pp []float64
  26. vv []int
  27. }{
  28. {
  29. vals: []int{15, 20, 35, 40, 50},
  30. pp: []float64{0.05, 0.3, 0.4, 0.5, 1},
  31. vv: []int{15, 20, 20, 35, 50},
  32. },
  33. {
  34. vals: []int{3, 6, 7, 8, 8, 10, 13, 15, 16, 20},
  35. pp: []float64{0.25, 0.5, 0.75, 1},
  36. vv: []int{7, 8, 15, 20},
  37. },
  38. {
  39. vals: []int{3, 6, 7, 8, 8, 9, 10, 13, 15, 16, 20},
  40. pp: []float64{0.25, 0.5, 0.75, 1},
  41. vv: []int{7, 9, 15, 20},
  42. },
  43. }
  44. maxVal := 0
  45. for _, tst := range tests {
  46. for _, v := range tst.vals {
  47. if maxVal < v {
  48. maxVal = v
  49. }
  50. }
  51. }
  52. for _, tst := range tests {
  53. d := New(maxVal + 1)
  54. for _, v := range tst.vals {
  55. d.Record(v)
  56. }
  57. for i, p := range tst.pp {
  58. got, want := d.Percentile(p), tst.vv[i]
  59. if got != want {
  60. t.Errorf("d=%v, d.Percentile(%f)=%d, want %d", d, p, got, want)
  61. }
  62. }
  63. }
  64. }
  65. func TestRace(t *testing.T) {
  66. const N int = 1e3
  67. const parallel = 2
  68. d := New(N)
  69. var wg sync.WaitGroup
  70. wg.Add(parallel)
  71. for i := 0; i < parallel; i++ {
  72. go func() {
  73. for i := 0; i < N; i++ {
  74. d.Record(i)
  75. }
  76. wg.Done()
  77. }()
  78. }
  79. for i := 0; i < N; i++ {
  80. if p := d.Percentile(0.5); p > N {
  81. t.Fatalf("d.Percentile(0.5)=%d, expected to be at most %d", p, N)
  82. }
  83. }
  84. }