我必须使用带有float和double参数的泛型类来编写矩阵乘法函数,然后比较结果和时间。到目前为止我有这个:
public MyMatrix<T> multiply(MyMatrix<T> secondMatrix) {
MyMatrix<T> resultMatrix = new MyMatrix<T>(classType, this.rows, secondMatrix.columns);
if (classType.equals(Float.class)) {
float sum = 0;
for (int c = 0 ; c < rows; c++ ) {
for (int d = 0 ; d < secondMatrix.columns; d++ ) {
for (int k = 0 ; k < secondMatrix.rows; k++ ) {
sum = sum + this.matrix[c][k].floatValue() * secondMatrix.matrix[k][d].floatValue(); }
Float wynik = sum;
resultMatrix.matrix[c][d] = (T)result;
sum=0; } } }
else if (classType.equals(Double.class) (...) same but double instead float
结果可能是正确的,但问题是双参数函数更快。
这是我如何衡量时间:
start = System.nanoTime();
MyMatrix<Float> matrixFloat = matrixAfloat.multiply(vectorFloat);
end = System.nanoTime() - start;
double timeFloat = end / 1000000000.0;
start = System.nanoTime();
MyMatrix<Double> matrixDouble = matrixAdouble.multiply(vectorDouble);
end = System.nanoTime() - start;
double timeDouble = end / 1000000000.0;
我可能犯错的任何想法?