[英]Fibonacci Hash Function in java
I found this article https://probablydance.com/2018/06/16/fibonacci-hashing-the-optimization-that-the-world-forgot-or-a-better-alternative-to-integer-modulo/我发现这篇文章https://probablydance.com/2018/06/16/fibonacci-hashing-the-optimization-that-the-world-forgot-or-a-better-alternative-to-integer-modulo/
I am trying to implement this function in Java to get numbers from [0,1].我正在尝试在 Java 中实现此函数以从 [0,1] 获取数字。
My first approach was :我的第一种方法是:
public static double index_for_hash2(double hash)
{
double golden_ratio= ((1+Math.sqrt(5))/2);
double num = hash*golden_ratio;
double final_number = num - (int)num;
return final_number;
}
but for some numbers, I am taking numbers greater than 1.但对于某些数字,我取的数字大于 1。
Then I tried this :然后我尝试了这个:
public static double ind_for_hash(int hash) {
BigInteger A = new BigInteger("11400714819323198485");
String hash2 = String.valueOf(hash);
BigInteger B = new BigInteger(hash2);
BigInteger mult = A.multiply(B);
BigInteger mask = new BigInteger("13061404503765839921");
BigInteger mult1 = mult.and(mask);
System.out.println(mult1.bitLength());
BigInteger result = mult1.shiftRight(61);
System.out.println(result);
return result.doubleValue();
}
But all I am taking is a number (0,7) because I have 3 bits.但我所取的只是一个数字 (0,7),因为我有 3 位。 If I shift 63 I will take only 1 bit so I will only have 0 and 1. I won't have a number in a ranger from (0,1).
如果我移动 63,我只需要 1 位,所以我只有 0 和 1。我不会在 (0,1) 的游侠中获得数字。 For input hash=2042988003 my output is: 1.1581403804622722E9 not in the wanted range(0,1).
对于输入哈希 = 2042988003,我的输出是:1.1581403804622722E9 不在想要的范围内(0,1)。
public static double index_for_hash2(double hash)
{
Double golden_ratio= ((1+Math.sqrt(5))/2);
Double num = hash*golden_ratio;
String sixLetter = num.toString().substring(0,16);
num = Double.parseDouble(sixLetter);
int fin_num = num.intValue();
double final_number = num - fin_num;
return final_number;
}
I came up with this solution and it seems to work.我想出了这个解决方案,它似乎有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.