Java 求两个向量余弦相似度计算代码
公式:
源码:
public Double getCosineSimilarity( List<Double> x, List<Double> y ){
double numerator = 0D;
for( int i = 0; i < x.size(); i++ ){
numerator += x.get( i ) * y.get( i );
}
double leftDenominator = 0D;
for( Double num : x ){
leftDenominator += num * num;
}
double rightDenominator = 0D;
for( Double num : y ){
rightDenominator += num * num;
}
return numerator / ( Math.sqrt( leftDenominator ) * Math.sqrt( rightDenominator ) );
}