Created
May 11, 2020 03:59
-
-
Save joriki/411b42ede3d3bdff9f31ab5a3be1925b to your computer and use it in GitHub Desktop.
Simulate the number of uniformly distributed quarter circle sectors required to cover a circle; see https://math.stackexchange.com/questions/3667404.
This file contains 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
import java.util.ArrayList; | |
import java.util.Iterator; | |
import java.util.List; | |
import java.util.Random; | |
public class Question3667404 { | |
final static long ntrials = 10000000; | |
final static Random random = new Random(); | |
static class Range { | |
double a; | |
double b; | |
public Range(double a,double b) { | |
this.a = a; | |
this.b = b; | |
} | |
public boolean contains (double x) { | |
return a <= x && x < b; | |
} | |
} | |
public static void main(String [] args) { | |
long count = 0; | |
for (long trial = 0;trial < ntrials;trial++) { | |
List<Range> ranges = new ArrayList<>(); | |
ranges.add(new Range(0.25,1)); | |
count++; | |
while (!ranges.isEmpty()) { | |
count++; | |
double beg = random.nextDouble(); | |
double end = beg + 0.25; | |
Iterator<Range> iterator = ranges.iterator(); | |
List<Range> newRanges = new ArrayList<>(); | |
while (iterator.hasNext()) { | |
Range range = iterator.next(); | |
if (range.contains (beg)) | |
newRanges.add(new Range(range.a,beg)); | |
if (range.contains(end)) | |
newRanges.add(new Range(end,range.b)); | |
if (beg < range.b && end > range.a) { | |
iterator.remove(); | |
ranges.addAll(newRanges); | |
break; | |
} | |
} | |
} | |
} | |
System.out.println(count / (double) ntrials); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment