
Percolation Simulation

This is a simulation of aspects of mathematical percolation theory.

For other percolation simulations, see Category:Percolation Simulations, or:
1D finite grid simulation
Mean run density 
2D finite grid simulations
Site percolation | Bond percolation | Mean cluster density

Let 



v


{\displaystyle v}

 be a vector of 



n


{\displaystyle n}

 values of either 1 or 0 where the probability of any
value being 1 is 



p


{\displaystyle p}

; the probability of a value being 0 is therefore 



1
−
p


{\displaystyle 1-p}

.
Define a run of 1s as being a group of consecutive 1s in the vector bounded
either by the limits of the vector or by a 0. Let the number of such runs in a given
vector of length 



n


{\displaystyle n}

 be 




R

n




{\displaystyle R_{n}}

.

For example, the following vector has 




R

10


=
3


{\displaystyle R_{10}=3}



[1 1 0 0 0 1 0 1 1 1]
 ^^^       ^   ^^^^^

Percolation theory states that





K
(
p
)
=

lim

n
→
∞



R

n



/

n
=
p
(
1
−
p
)


{\displaystyle K(p)=\lim _{n\to \infty }R_{n}/n=p(1-p)}


Task
Any calculation of 




R

n



/

n


{\displaystyle R_{n}/n}

 for finite 



n


{\displaystyle n}

 is subject to randomness so should be
computed as the average of 



t


{\displaystyle t}

 runs, where 



t
≥
100


{\displaystyle t\geq 100}

.

For values of 



p


{\displaystyle p}

 of 0.1, 0.3, 0.5, 0.7, and 0.9, show the effect of varying 



n


{\displaystyle n}


on the accuracy of simulated 



K
(
p
)


{\displaystyle K(p)}

.

Show your output here.

See also
 s-Run on Wolfram mathworld.
// version 1.2.10
 
import java.util.Random
 
val rand = Random()
const val RAND_MAX = 32767
 
// just generate 0s and 1s without storing them
fun runTest(p: Double, len: Int, runs: Int): Double {
    var cnt = 0
    val thresh = (p * RAND_MAX).toInt()
    for (r in 0 until runs) {
        var x = 0
        var i = len
        while (i-- > 0) {
            val y = if (rand.nextInt(RAND_MAX + 1) < thresh) 1 else 0
            if (x < y) cnt++
            x = y
        }
    }
    return cnt.toDouble() / runs / len
}
 
fun main(args: Array<String>) {
    println("running 1000 tests each:")
    println(" p\t   n\tK\tp(1-p)\t     diff")
    println("------------------------------------------------")
    val fmt = "%.1f\t%6d\t%.4f\t%.4f\t%+.4f (%+.2f%%)"
    for (ip in 1..9 step 2) {
        val p = ip / 10.0
        val p1p = p * (1.0 - p)
        var n = 100
        while (n <= 100_000) {
            val k = runTest(p, n, 1000)
            println(fmt.format(p, n, k, p1p, k - p1p, (k - p1p) / p1p * 100))
            n *= 10
        }
        println()
    }
}