示例代码
典型的数组处理代码
找出数组中最大的元素
double max = a[0];
for (int i = 1; i < a.length; i++) {
if (a[i] > max) max = a[i];
}
计算数组元素的平均值
int N = a.length;
double sum = 0.0;
for (int i = 0; i < N; i++)
sum += a[i];
double average = sum / N;
复制数组
int N = a.length;
double[] b = new double[N];
for (int i = 0; i < N; i++)
b[i] = a[i];
颠倒数组元素的顺序
int N = a.length;
for (int i = 0; i < N / 2; i++) {
double temp = a[i];
a[i] = a[N-1-i];
a[N-1-i] = temp;
}
方阵相乘
int N = a.length;
double[][] c = new double[N][N];
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
// 计算 行i 和 列j 的点乘
for (int k = 0; k < N ;k++)
c[i][j] += a[i][k] * b[k][j];
}
}
典型静态方法的实现
计算一个整数的绝对值
public static int abs(int x)
{
if (x < 0) return -x;
else return x;
}
计算一个浮点数的绝对值
public static double abs(double x) {
if (x < 0.0) return -x;
else return x;
}
判定一个数是否是素数
public static boolean isPrime(int N) {
if (N < 2) return false;
for (int i = 2; i * i <= N; i++) {
if (N % i == 0) return false;
}
return true;
}
计算平方根(牛顿迭代法)
public static double sqrt(double c) {
if (c < 0) return Double.NaN;
double err = 1e-15;
double t = c;
while (Math.abs(t - c / t) > err * t) {
t = (c / t + t) / 2.0;
}
return t;
}
计算直角三角形的斜边
public static double hypotenuse(double a, double b) {
return Math.sqrt(a * a + b * b);
}
计算调和级数
public static double H(int N) {
double sum = 0.0;
for (int i = 1; i <= N; i++) {
sum += 1.0 / i;
}
return sum;
}