我正在编写一个程序,使用穷举搜索和二分搜索来搜索英语词典。我必须打印出每个人的平均值。 这是两者的代码。我真的不认为问题在于 find 和 findUsingBinarySearch 本身。
public static double measureAverageExhaustiveSearchTime(String[] queries, String[] array){
//Measures the average number of microseconds (µs) needed to find each query, using exhaustive search.
long startTime = System.currentTimeMillis();
for(int i = 0; i < queries.length; i++){
find(queries[i], array);
}
long endTime = System.currentTimeMillis();
double elapsedTime = (endTime - startTime);
return (double)((elapsedTime/1000000000.0)/queries.length);
}
public static double measureAverageBinarySearchTime(String[] queries, String[] array){
//Measures the average number of microseconds (µs) needed to find each query, using binary search.
long startTime = System.nanoTime();
for(int i = 0; i < queries.length; i++){
findUsingBinarySearch(queries[i], array);
}
long endTime = System.nanoTime();
double elapsedTime = (endTime - startTime);
return (double)((elapsedTime/1000000000.0)/queries.length);
//(double)(elapsedTime * 1000)/(queries.length);
}
我的输出只是:
详尽的搜索: NaN 秒
二分搜索: NaN 秒
彻底搜索失败: NaN 秒
二进制搜索失败: NaN 秒
<小时/>当我使用更小的文件时,我得到了这个!
详尽的搜索: 0.0 秒
二分搜索: 2.1E-6秒
彻底搜索失败: 1.0E-10秒
二进制搜索失败: 1.4E-6秒
这是我调用该方法的方式,使用字典作为两个参数,因为我试图测试数组进行二分搜索本身需要多长时间。我还使用了字典的副本,每个单词都附加了“zzz”,以方便失败的二进制和穷举搜索。
System.out.println("EXHAUSTIVE SEARCH: ");
System.out.println(measureAverageExhaustiveSearchTime(dictionary, dictionary)+" seconds");
System.out.println("BINARY SEARCH: ");
System.out.println(measureAverageBinarySearchTime(dictionary, dictionary)+" seconds");
System.out.println("FAILED EXHAUSTIVE SEARCH: ");
System.out.println(measureAverageExhaustiveSearchTime(dictionaryzzz, dictionary) + " seconds");
System.out.println("FAILED BINARY SEARCH: ");
System.out.println(measureAverageBinarySearchTime(dictionaryzzz, dictionary)+" seconds");
我不确定如何解决这个问题。
最佳答案
如果您尝试将毫秒转换为微秒,则应该乘以而不是除以 1000。
您的measureAverageExhaustiveSearchTime代码:
return (double)((elapsedTime/1000000000.0)/queries.length);
这应该是:
return (double)((elapsedTime*1000.0)/queries.length);
此外,在求解 elapsedTime
时,我会通过将其转换为 double 来避免转换 startTime
和 endTime
长数据类型。尝试保留一种数据类型。数据类型转换有时会导致结果被截断或意外的值下限。
关于java - 在 Java 中计算耗时时收到 NaN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20168292/