看JAVA语言程序设计基础,因为以前学习的都是C++, 总体基本上相似。不过这本书里有几个比较有意思的小地方,比如书中写的最小化数值误差(4.7),书中说在大数之前先增加小数是减少误差的方法。如:
//第一种方法求0.01到1之间递增的数列之和 for(float i = 0.01f; i<= 1.0f; i = i + 0.01f) { sum +=i; } //第二种 for(double i = 0.01; i<= 1.0; i = i + 0.01) { sum +=i; } //第三种 currentValue = 0.01; for(int i = 0; i< 100; i++) { sum += currentValue; currentValue += 0.01; } //第四种 currentValue = 1.0; for(int i = 0; i< 100; i++) { sum += currentValue; currentValue -= 0.01; }
public class ComputeArea { public static void main(String[] args) { final int numPoint = 10000000; int rHitNum = 0; for (int i = 0; i < numPoint; i++) { double x = Math.random() * 2 - 1; double y = Math.random() * 2 - 1; if ((Math.pow(x, 2) + y * y) <= 1) { rHitNum++; } } double pi = 4 * ((double)rHitNum / (double)numPoint); //记得强制类型转化为double再除,书中好像有问题 System.out.printf("the PI is : %f", pi); } }