查找分子或分母不大于一亿的分数Π
private static final int MAX_N = 100000000;
private static void findPIByDivider() {
Log.d("findPI", "findPIByDivider start MAX_N=" + MAX_N);
long curtime = System.currentTimeMillis();
double lastRet = 1;
int selectI = 0, selectJ = 0;
double finalRet = 0;
for (int i = 3; i <= MAX_N; i++) {
int m = (int) (i / Math.PI);
for (int j = m; j <= m + 1; j++) {
double di = i;
double ret = Math.abs(di / j - Math.PI);
if (ret < lastRet) {
lastRet = ret;
selectI = i;
selectJ = j;
finalRet = di / j;
}
}
if( isPowerOfTen(i) || i == MAX_N) {
Log.d("findPI", "i=" + String.format("%-12s", i) + " fraction = " + String.format("%12s", selectI) +
" / " + String.format("%-12s", selectJ) + " finalRet=" + finalRet);
}
}
Log.d("findPI", "findPIByDivider end. PI=" + Math.PI + " use time=" + (System.currentTimeMillis() - curtime));
}
private static void findPIByMulti() {
Log.d("findPI", "findPIByMulti start MAX_N=" + MAX_N);
long curtime = System.currentTimeMillis();
double lastRet = 1;
int selectI = 0, selectJ = 0;
double finalRet = 0;
for (int i = 1; i <= MAX_N; i++) {
int m = (int) (i * Math.PI);
for (int j = m; j <= m + 1; j++) {
double di = i;
double ret = Math.abs(j / di - Math.PI);
if (ret < lastRet) {
lastRet = ret;
selectI = i;
selectJ = j;
finalRet = j / di;
}
}
if( isPowerOfTen(i) || i == MAX_N) {
Log.d("findPI", "i=" + String.format("%-12s", i) + " fraction = " + String.format("%12s", selectJ) +
" / " + String.format("%-12s", selectI) + " finalRet=" + finalRet);
}
}
Log.d("findPI", "findPIByMulti end. PI=" + Math.PI + " use time=" + (System.currentTimeMillis() - curtime));
}
private static boolean isPowerOfTen(int num) {
int tenPower = 1;
for (int i = 1; i < 12; i++) {
tenPower *= 10;
if (num == tenPower) {
return true;
}
}
return false;
}
结果如下:
反复运行后,会发现在做大量运算时,乘法要比除法的效率高一些
本站资源均来自互联网,仅供研究学习,禁止违法使用和商用,产生法律纠纷本站概不负责!如果侵犯了您的权益请与我们联系!
转载请注明出处: 免费源码网-免费的源码资源网站 » 查找最佳分数Π
发表评论 取消回复