Utilisation de BigDecimal en Java pour calculer le nombre PI jusqu'à 200 chiffres décimaux
Pour estimer le nombre PI, je veux utiliser en particulier la méthode Monte Carlo s'appliquant à un jeu de fléchettes avec un cercle de rayon 1 à l'intérieur d'un carré 1x1. Plus description peut être trouvée ici. Je veux un code Java pour estimer PI jusqu'à 200 chiffres. J'ai utilisé BigDecimal
mais il montre 49 chiffres décimaux et met zéro nombre pour le reste. J'apprécie toute aide.
import java.util.*;
import java.math.BigDecimal;
public class PiFinder {
// description
public static void main(String[] args) {
Scanner iteration = new Scanner(System.in);
System.out.print("Enter the number of iteration: ");
int NoThrows = iteration.nextInt();
BigDecimal PI = new BigDecimal(PIcalculation(NoThrows));
PI = PI.setScale(200);
// Difference of our estimated PI and the actual PI
BigDecimal Difference = new BigDecimal(0);
BigDecimal actualPI = new BigDecimal(Math.PI);
System.out.println("Actual PI: " + actualPI);
Difference = PI.subtract(actualPI);
// Display results
System.out.println("The Number of Throws = " + NoThrows);
System.out.println("***************************");
System.out.println("Estimated PI = " + PI);
System.out.println("Difference = " + Difference);
}
// Deteremine a thrown dart is inside the circle
public static boolean insideCircle(double pos_X, double pos_Y) {
double distance = Math.sqrt((pos_X * pos_X) + (pos_Y * pos_Y));
return (distance < 1.0);
}
public static double PIcalculation(int NoThrows) {
Random randomGen = new Random(System.currentTimeMillis());
int hits = 0;
double PI = 0;
for (int i = 1; i <= NoThrows; i++) {
double pos_X = (randomGen.nextDouble()) * 2 - 1.0;
double pos_Y = (randomGen.nextDouble()) * 2 - 1.0;
if (insideCircle(pos_X, pos_Y)) {
hits++;
}
}
double dthrows = NoThrows;
// the formule
PI = (4.0 * (hits / dthrows));
return PI;
}
}
2
1 answers
Votre picalcul renvoie un double, vous ne pouvez pas vous attendre à avoir plus de précision avec cela.
Utilisez BigDecimal partout, si vous voulez aller plus loin.
, Mais de toute façon avec cette méthode, même avec 10^10 lancers, vous n'avez que 10 décimales.
Les 49 décimales que vous aviez avec votre double, étaient dues au double manque de précision
3
Author: yunandtidus, 2014-12-23 08:15:37