Skip to content

Instantly share code, notes, and snippets.

@joriki
Created September 6, 2018 00:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joriki/26221ca553033a36cc31fb83b5fa9953 to your computer and use it in GitHub Desktop.
Save joriki/26221ca553033a36cc31fb83b5fa9953 to your computer and use it in GitHub Desktop.
Confirm that the probability for a random line in a square to be the diagonal of a square contained in the square is 2/3; see https://math.stackexchange.com/questions/2906823.
public class Question2906823 {
final static int ntrials = 100000000;
public static void main (String [] args) {
int count = 0;
for (int n = 0;n < ntrials;n++) {
double x1 = Math.random ();
double y1 = Math.random ();
double x2 = Math.random ();
double y2 = Math.random ();
double mx = (x1 + x2) / 2;
double my = (y1 + y2) / 2;
double dx = x1 - mx;
double dy = y1 - my;
double xa = mx + dy;
double ya = my - dx;
double xb = mx - dy;
double yb = my + dx;
if (inRange (xa) && inRange (ya) && inRange (xb) && inRange (yb))
count++;
}
System.out.println (count / (double) ntrials);
}
static boolean inRange (double x) {
return 0 <= x && x <= 1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment