Java-基于整数
该程序不使用pi,并且不调用任何外部函数-甚至sqrt。它仅使用简单的算术题- ,,+
和。此外,除了缩放步骤外,它还专门处理整数。它基本上将球体分成小立方体,并计算盒子外的立方体。-
*
/
public class Box {
private static final int MIN = 10000;
private static final int MAX = MIN * 2;
private static final int[] SQ = new int[MAX * MAX + 1];
static {
int t = 1;
for (int i = 1; i <= MAX; ++i) {
while (t < i * i) SQ[t++] = i - 1;
}
SQ[MAX * MAX] = MAX;
}
public static long outsideInt(int r, int w, int z) {
int r2 = r * r;
int o = z - r + 1;
if (w < r * 2) {
int t = 1 - SQ[r2 - w * w / 4];
if (t < o) o = t;
}
long v = 0;
for (int i = o; i <= r; ++i) {
int d = r2 - i * i;
int j0 = SQ[d];
v += 1 + 3 * j0;
for (int j = 1; j <= j0; ++j)
v += 4 * SQ[d - j * j];
}
return v;
}
public static double outside(double x, double y, double z, double d) {
double f = 1;
double w = x < y ? x : y;
double r = d / 2;
while (r < MIN) {
f *= 8;
r *= 2;
w *= 2;
z *= 2;
}
while (r > MAX) {
f /= 8;
r /= 2;
w /= 2;
z /= 2;
}
return outsideInt((int) r, (int) w, (int) z) / f;
}
public static void main(final String... args) {
System.out.println(outside(1, 1, 1, 1));
System.out.println(outside(1, 1, 0, 1));
System.out.println(outside(1, 1, 0.5, 1));
System.out.println(outside(1, 0.999, 1, 1));
System.out.println(outside(0.1, 1, 1, 0.5));
}
}
输出:
0.0
0.5235867850933005
0.26178140856157484
0.27938608275528054
0.06542839088004015
以这种形式,该程序需要超过2GB的内存(可在-Xmx2300m
此处使用),而且速度很慢。它使用内存来预先计算一堆平方根(算术);这不是真正必要,但如果没有这样做,它将慢很多。为了同时提高内存需求和速度,请减小MIN
常量的值(尽管那样会降低精度)。