【发布时间】:2018-10-19 10:56:18
【问题描述】:
我需要使用 汉明距离 来比较两个相同大小的布隆过滤器 BF1 和 BF2 的相似性,它表示两组之间的距离作为绽放距离
B(BF1,BF2)=one(BF1 & BF2)/SIZEOF(BF1)
one() 函数计算 ANDed 布隆过滤器中设置的位数。
我从Path similarity evaluation using Bloom filters 第 3 节(第 4 页。相似度指标)中采用了这个公式。
我已经实现了以下 c 代码来执行此操作,但它肯定无法正常工作。
#include <stdlib.h>
#include <stdio.h>
const int BF_LEN= 1024;
char *BF1;//=malloc(BF_LEN*sizeof(char));
char *BF2;//=malloc(BF_LEN*sizeof(char));
char *buf;//=malloc(BF_LEN*sizeof(char));
char *buf_ptr=NULL;
int set_bits_count=0;
float similarity=0.0;
u_int32_t NumberOfSetBits(u_int32_t i)
{
return (((((i - ((i >> 1) & 0x55555555)) & 0x33333333) + (((i - ((i >> 1) & 0x55555555)) >> 2) & 0x33333333) + (((i - ((i >> 1) & 0x55555555)) & 0x33333333) + (((i - ((i >> 1) & 0x55555555)) >> 2) & 0x33333333) >> 4)) & 0x0F0F0F0F) * 0x01010101) >> 24;
}
void main()
{
BF1=malloc(BF_LEN*sizeof(char));
BF2=malloc(BF_LEN*sizeof(char));
buf=malloc(BF_LEN*sizeof(char));
//Edit2:initialize them to 0
for(int j=0;j<BF_LEN;j++)
{
BF1[j]='\0';
BF2[j]='\0';
buf[j]='\0';
}
BF1="BF1 is filled with some characters";
BF2="BF2 is filled with some characters and more";
for(int j=0; j<BF_LEN; j++)
{
buf[j]=BF1[j]&BF2[j];
}
buf_ptr=buf;
for(int m=0; m<BF_LEN; m++) //This is for the **one()** function
set_bits_count+=NumberOfSetBits(*buf_ptr++);
similarity=1-set_bits_count/(float)BF_LEN;
printf("%.2f",similarity);
//Edit1: Following Comments
free(BF1);
free(BF2);
free(buf);
}
NumberOfSetBits() 采用自Set bit counter
【问题讨论】:
-
你得到了什么结果?最好的猜测是,在进行除法之前,您需要将 set_bits_count 或 BF_LEN 之一转换为浮点数,否则您将得到整数除法。
-
@Rup 我将其更正为您的评论。仍然没有正确的结果。
-
与您的问题无关:: 用
BF1="BF1 is filled with some characters";覆盖malloc时出现内存泄漏 -
@kiranBiradar 我该如何解决?我是 c 的新手。
-
Kiran 的观点是你没有释放任何缓冲区,特别是你将 BF1 指针重新分配给你的常量字符串并丢失你刚刚分配的指针(如上所述,我假设这是不是你实际在做什么?)。如果这是程序的结尾,那么这并不是真正的问题:操作系统将回收所有分配的内存。如果您继续做更多的事情,您应该在从 malloc() 返回的指针上调用 free()。
标签: c bitwise-operators hamming-distance bitwise-and bloom-filter