より簡単に2つのことを行うために利用可能なライブラリが必要だと思います.A)倍精度の場合は配列のモードを見つけ、B)特定の周波数に達するまで精度を適切に低下させます。
したがって、次のような配列を想像してください。
double[] a = {1.12, 1.15, 1.13, 2.0, 3.4, 3.44, 4.1, 4.2, 4.3, 4.4};
周波数 3 を探していた場合、小数点以下 2 桁から 1 桁になり、最終的にモードとして 1.1 が返されます。周波数要件が 4 の場合、モードとして 4 が返されます。
希望どおりに動作し、期待どおりの結果を返す一連のコードがありますが、これを達成するためのより効率的な方法、または同じことを行うのに役立つ既存のライブラリが必要だと感じています。添付されているのは私のコードです。私が取るべきだったさまざまなアプローチについての考え/コメントに興味があります....精度がどれだけ低下するかを制限するために、反復をリストしています。
public static double findMode(double[] r, int frequencyReq)
{
double mode = 0d;
int frequency = 0;
int iterations = 4;
HashMap<Double, BigDecimal> counter = new HashMap<Double, BigDecimal>();
while(frequency < frequencyReq && iterations > 0){
String roundFormatString = "#.";
for(int j=0; j<iterations; j++){
roundFormatString += "#";
}
DecimalFormat roundFormat = new DecimalFormat(roundFormatString);
for(int i=0; i<r.length; i++){
double element = Double.valueOf(roundFormat.format(r[i]));
if(!counter.containsKey(element))
counter.put(element, new BigDecimal(0));
counter.put(element,counter.get(element).add(new BigDecimal(1)));
}
for(Double key : counter.keySet()){
if(counter.get(key).compareTo(new BigDecimal(frequency))>0){
mode = key;
frequency = counter.get(key).intValue();
log.debug("key: " + key + " Count: " + counter.get(key));
}
}
iterations--;
}
return mode;
}
編集
frequencyPaulo のコメントによると、質問を言い換える別の方法: 目標は、近隣の半径ができるだけ小さい、近隣に少なくとも配列要素がある数値を見つけることです。