Repository: JuliaStats/HypothesisTests.jl (julia)

Issue:
p val > 1 in ExactMannWhitneyUTest 
```
A = [ 1.34937, 1.75722,0.276514, 1.04546 , 1.69085 , 0.738085, 2.36313 ]
B = [ 2.62325 , 1.16533 , 1.1327  ,  0.728714]

julia>ExactMannWhitneyUTest(A,B)
Exact Mann-Whitney U test
-------------------------
Population details:
    parameter of interest:   Location parameter (pseudomedian)
    value under h_0:         0
    point estimate:          0.20035500000000006

Test summary:
    outcome with 95% confidence: fail to reject h_0
    two-sided p-value:           1.0727272727272728

Details:
    number of observations in each group: [7, 4]
    Mann-Whitney-U statistic:             14.0
    rank sums:                            [41.0, 25.0]
    adjustment for ties:                  0.0
```

Pull request description:
Fix taken from [here](https://github.com/SurajGupta/r-source/blob/a28e609e72ed7c47f6ddfbb86c85279a0750f0b7/src/library/stats/R/wilcox.test.R#L76) in the R source code. 

Tests seem to fail for FischerExactTest for unrelated reasons.

Patch:
diff --git a/src/mann_whitney.jl b/src/mann_whitney.jl
index da1e959e..df3a7157 100644
--- a/src/mann_whitney.jl
+++ b/src/mann_whitney.jl
@@ -141,10 +141,11 @@ function pvalue(x::ExactMannWhitneyUTest; tail=:both)
         # cannot account for ties
         if tail == :both
             if x.U < x.nx * x.ny / 2
-                2 * pwilcox(x.U, x.nx, x.ny, true)
+                p = pwilcox(x.U, x.nx, x.ny, true)
             else
-                2 * pwilcox(x.U - 1, x.nx, x.ny, false)
+                p = pwilcox(x.U - 1, x.nx, x.ny, false)
             end
+            min(2 * p, 1.0)
         elseif tail == :left
             pwilcox(x.U, x.nx, x.ny, true)
         else # tail == :right
@@ -226,7 +227,8 @@ function pvalue(x::ApproximateMannWhitneyUTest; tail=:both)
     if x.mu == x.sigma == 0
         1.0
     elseif tail == :both
-        2 * ccdf(Normal(), abs(x.mu - 0.5 * sign(x.mu))/x.sigma)
+        p = 2 * ccdf(Normal(), abs(x.mu - 0.5 * sign(x.mu))/x.sigma)
+        min(p, 1.0)
     elseif tail == :left
         cdf(Normal(), (x.mu + 0.5)/x.sigma)
     else # tail == :right


Test patch:
diff --git a/test/mann_whitney.jl b/test/mann_whitney.jl
index 5076b35c..0f614901 100644
--- a/test/mann_whitney.jl
+++ b/test/mann_whitney.jl
@@ -53,4 +53,25 @@ end
 @testset "Issue #39" begin
     @test abs(@inferred(pvalue(ExactMannWhitneyUTest(Float32[1:10;], Float32[2:11;]))) - 0.5096) <= 1e-4
 end
+
+@testset "Issue #126 pvalues above 1" begin
+	A = [1.34937, 1.75722,0.276514, 1.04546, 1.69085, 0.738085, 2.36313]
+	B = [2.62325, 1.16533, 1.1327, 0.728714]
+
+	m = ExactMannWhitneyUTest(A,B)
+	p = @inferred(pvalue(m; tail = :both))
+	@test p == 1
+
+	A = [12,10,7,6,3,1]
+	B = [11,9,8,5,4,2]
+
+	m = MannWhitneyUTest(A,B)
+	p = @inferred(pvalue(m; tail = :both))
+
+	@test p == 1
+
+	m = ApproximateMannWhitneyUTest(A, B)
+	p = @inferred(pvalue(m; tail = :both))
+end
+
 end