import java.util.*;
public class MontePI {
private int _count;
public MontePI(int count) {
_count = count;
System.out.println("Count : "+_count);
}
// =============================================================
// 実数演算の実行
// =============================================================
/**
* 実数値を用いて円周率計算を実行します.
* 1辺が 1.0 の正方形の中でランダムに点を打ち、その点が中心
* (0, 0)、半径 1.0 の円の領域に含まれているかどうかを評価してい
* ます。
*
* πr^2 / 4 : 1 = n : _count
*/
private void calculateDouble() {
Random rand = new Random(); // 乱数生成オブジェクト
double x, y; // 正方形の中の点
int n = 0; // 円領域内の点数
int i; // ループカウンタ
double r2 = 1.0 * 1.0; // 円の半径の二乗値
// 単位円の中に含まれる点の数を数え上げる
for(i = 0; i < _count; i++) {
x = rand.nextDouble();
y = rand.nextDouble();
if(x * x + y * y < r2) n++;
}
// 円周率を計算する
double pi = 4.0 * n / (double)_count;
double diff = 3.14159265358979 - (4.0 * n / (double)_count);
System.out.println( "PI : " + pi );
System.out.println( "Diff : " + diff );
}
// =============================================================
// 整数演算の実行
// =============================================================
/**
* 整数値を用いて円周率計算を実行します.
* この演算では1辺が 0x7FFF (32,767) の正方形中でランダムに採取
* した点が、中心 (0, 0)・半径 0x7FFF の円の領域内に含まれている
* かどうかを計算しています。この半径 0x7FFF は二乗値が int の
* 精度内に収まるという理由で採用しました。
*/
private void calculateInt() {
Random rand = new Random(); // 乱数生成オブジェクト
int x, y; // 正方形の中の点
int n = 0; // 円領域内の点数
int i; // ループカウンタ
int r2 = 0x7FFF * 0x7FFF; // 円の半径の二乗値
// 半径 0x7FFF の円の中に含まれる点の数を数え上げる
for(i = 0; i < _count; i++){
x = rand.nextInt() & 0x7FFF;
y = rand.nextInt() & 0x7FFF;
if(x * x + y * y < r2) n++;
}
// 円周率を計算する
double pi = 4.0 * n / (double)_count;
double diff = 3.14159265358979 - (4.0 * n / (double)_count);
System.out.println( "PI : " + pi );
System.out.println( "Diff : " + diff );
}
public static void main(String[] args) {
int count = Integer.parseInt(args[0]);
MontePI m = new MontePI(count);
long s;// 計算開始時刻
long e;// 計算終了時刻
long t;// 計算時間
s = System.currentTimeMillis();
m.calculateDouble();
e = System.currentTimeMillis();
t = e - s;
System.out.println( "Time : " + t );
s = System.currentTimeMillis();
m.calculateInt();
e = System.currentTimeMillis();
t = e - s;
System.out.println( "Time : " + t );
}
}
*メニュー
最新の20件
2018-04-17
2012-01-07
2011-12-07
2011-11-03
2011-10-20
2011-10-18
2014-07-13
2013-08-10
2012-01-26
2012-01-25
2012-01-24
2012-01-23
2012-01-21
2012-01-20
2012-01-19
2012-01-17
2012-01-14
2012-01-13
2012-01-09
人気の10件
- counter: 545
- today: 1
- yesterday: 0
- online: 1