Created
January 29, 2014 22:23
-
-
Save jgdoncel/0219394a187a5cb776c5 to your computer and use it in GitHub Desktop.
Estimar el valor de Pi usando el método de la "Aguja de Buffon"
http://http://es.wikipedia.org/wiki/Aguja_de_Buffon
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
// Tomar una aguja de 1cm y un papel con líneas paralelas a 2cm | |
// Lanzar la aguja sobre el papel, cada vez que la aguja corta una linea | |
// cuenta como un acierto | |
// pi (aprox) = intentos / aciertos | |
import java.util.Random; | |
import java.util.Scanner; | |
public class BuffonPiEstimation | |
{ | |
public static void main(String[] args) | |
{ | |
System.out.println("Aguja de Buffon"); | |
System.out.println("Introducir número de lanzamientos: "); | |
Scanner in = new Scanner(System.in); | |
int tries = in.nextInt(); | |
Random generator = new Random(42); | |
int hits = 0; | |
for (int i = 0; i < tries; i++) { | |
// Generar yLow la distancia de un extremo de la aguja a la línea | |
double yLow = generator.nextDouble()*2; | |
// Generar un ángulo entre 0 y 180 grados | |
double angle = generator.nextDouble()*180; | |
// Obtener la altura del otro extremo de la aguja | |
double yHigh = yLow + Math.sin(Math.toRadians(angle)); | |
// Si el extremo está a mayor altura que la siguiente linea | |
// es un acierto | |
if (yHigh >= 2) { | |
hits ++; | |
} | |
} | |
double piEstimate = (float) tries / hits; | |
System.out.println(); | |
System.out.println(piEstimate); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment