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/
I am trying to implement this function in Java to get numbers from [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.
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. 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). For input hash=2042988003 my output is: 1.1581403804622722E9 not in the wanted range(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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.