4
$\begingroup$

I have implemented a simple version of the congruential method, and now I want to test if the generated numbers are distributed uniformly using the KS test.

First I did a simple test

R.ks_test(U1, "punif")

but this gave an incredible small p-value. Then I realised that my congruential method yields numbers in the range of -1 to 1, and I suspect the default ks test in R checks for uniformity between 0 and 1.

Can I tell R to check for uniformity between -1 and 1, or should I simply just scale my values to be between 0 and 1?

I am using the R type provider in F# but it shouldn't make much of a difference

..and sorry if this is a simple question, my statistics kungfu is incredible weak :)

$\endgroup$

1 Answer 1

8
$\begingroup$

You can specify the parameters of your distribution into the ks.test. Here is an example for testing the uniform (-1,1) distribution.

x<-runif(100,-1,1)
ks.test(x,"punif",-1,1)




 One-sample Kolmogorov-Smirnov test
        data:  x
        D = 0.082848, p-value = 0.4986
        alternative hypothesis: two-sided

Αnd here is a visualization of the test.

  library(ggplot2)
    set.seed(1)
    x<-runif(100,-1,1)
    dd<-data.frame(x)
    ks.test(x,"punif",-1,1)

    ed <- ecdf(dd$x)
    maxdiffidx <- which.max(abs(ed(dd$x)-punif(dd$x,-1,1)))
    maxdiffat <- dd$x[maxdiffidx]

    p<-ggplot(aes(x),data=dd)+stat_ecdf()+theme_bw()+stat_function(fun=punif,args=list(-1,1))
    p<-p+labs(title="ECDF and theoretical CDF")+geom_vline(x=maxdiffat, lty=2)
    p

enter image description here

The vertical line corresponds to the maximum distance between the ECDF and the theoretical CDF, which is the KS statistic.

The ks.test can be adapted to test for whichever distribution you like by adding the proper arguments, just like I have done above. This will give you what you are looking for, I believe.

$\endgroup$
1
  • 2
    $\begingroup$ Thanks for the great answer. Just an update. It should be (maybe this is new as this answer is already some years old): p<- labs(title="ECDF and theoretic)al CDF"+ geom_vline(xintercept=maxdiffat, lty=2). Else you get an error if u use x instead of xintercept. $\endgroup$
    – kn1g
    Commented May 21, 2020 at 13:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.