2008年8月29日 星期五

算出PI

注意:要計算很久,會把CPU資源吃光光
code
package javahomework;

import javax.swing.JOptionPane;

public class HW12 {
public static void main(String arg[]) {
double p = 0, input = 1e10;
int x = -1;
for (double i = 0; i < input; i++) {
x *= -1;
// 4x(1-1/3+1/5-1/7+1/9...)
p += 4 * ((1 / (2 * i + 1)) * x);
}
p -= p % 0.0000000001;
JOptionPane.showMessageDialog(null, "PI is " + p);
}
}

沒有留言: