double を使用してバイナリ ツリーを実装しようとしていますが、double の比較が正しくないと思います。int をフィードすると、正しく動作します。ただし、小数点以下の桁数が多い double を挿入すると、segfault が発生します。
私の挿入関数は次のようになります。
int BinaryTree::insert_node(double val, char *str){;
return insert_node_helper(this->root, val, str);
}
int BinaryTree::insert_node_helper(TreeNode *&node, double val, char *str){
if(node == NULL){
node = new TreeNode;
node->val = val;
node->str = strdup(str);
node->left = NULL;
node->right = NULL;
return 0;
}else if(val > node->val){
return insert_node_helper(node->right, val, str);
}else{
return insert_node_helper(node->left, val, str);
}
return 1;
}
TreeNode の定義:
struct TreeNode {
double val;
char *str;
TreeNode *left;
TreeNode *right;
};
呼び出しコード:
void HashTable::chi_squared(){
int numTokens = numBigrams + 1;
BinaryTree topBigrams;
int treeInsertions = 0;
//indices for confusion matrix
int o11, o12, o21, o22 = 0;
int w1, w2, notW1, notW2 = 0;
double e11, e12, e21, e22 = 0;
double x2 = 0;
for(int i = 0; i < size; i++){
if(table[i] != NULL){
TokenList *temp = table[i]->tl;
while(temp != NULL){
Entry *temp2 = search(temp->str);
if(temp2 == NULL){
printf("string ( %s ) \n", temp->str);
temp = temp->next;
continue;
}
o11 = temp->occurrences; //total occurrences of word1 followed by word2
o21 = table[i]->occurrences - temp->occurrences; //total occurrences of word1 not followed by word2
o12 = search(temp->str)->occurrences - temp->occurrences; //total occurrences of not word1 followed by word2
o22 = numTokens - o11 - o12 - o21; //total occurrences of not word1 followed by not word2
w1 = table[i]->occurrences;
w2 = search(temp->str)->occurrences;
notW1 = numTokens - w1;
notW2 = numTokens - w2;
e11 = (w1 / (double)numTokens) * (w2 / (double)numTokens) * numTokens;
e12 = (notW1 / (double)numTokens) * (w2 / (double)numTokens) * numTokens;
e21 = (w1 / (double)numTokens) * (notW2 / (double)numTokens) * numTokens;
e22 = (notW1 / (double)numTokens) * (notW2 / (double)numTokens) * numTokens;
x2 = (pow((o11 - e11), 2) / (double)e11) +
(pow((o12 - e12), 2) / (double)e12) +
(pow((o21 - e21), 2) / (double)e21) +
(pow((o22 - e22), 2) / (double)e22);
x2 /= 100;
if(x2 >= 50){
if(treeInsertions < 100){
topBigrams.insert_node(x2, strcat(strcat(temp->str, " "), table[i]->str));
treeInsertions++;
}else if(x2 > topBigrams.find_min()->val){
topBigrams.replace_min(x2, strcat(strcat(temp->str, " "), table[i]->str));
}
temp = temp->next;
}
}
}
}
x2 は通常次のようになります。
どんな助けでも大歓迎です!