Created
September 4, 2017 07:46
-
-
Save simbo1905/1d7560ddb729b20c45c8daf7e068a975 to your computer and use it in GitHub Desktop.
The probability that two random numbers in the range [0,1] are 0.35 apart.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* The probability that two numbers in the range [0,1] are 0.35 apart. | |
* | |
* See discussion at https://math.stackexchange.com/a/2182330 | |
* Which explains this chart | |
* http://www.mathsisfun.com/data/grapher-equation.html?func1=x-y%3D0.35&func2=y-x%3D0.35&xmin=-0.2147&xmax=1.512&ymin=-0.01944&ymax=1.276 | |
*/ | |
object InterruptProbability { | |
import scala.util.Random.nextFloat | |
def main(args: Array[String]): Unit = { | |
val samples = 1e7.toInt | |
val distance = 0.35f | |
val percent = twoNodes(samples,distance) | |
println(f"two nodes $percent%1.2f") | |
} | |
private def twoNodes(samples: Int, distance: Float) = { | |
val hits = Stream.continually((nextFloat(), nextFloat())).take(samples).foldLeft(0) { | |
case (count, (x, y)) if Math.abs(x - y) > distance => count + 1 | |
case (count, _) => count | |
} | |
100 * hits.toFloat / samples | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment