#include <stdio.h>
typedef struct {
double low;
double high;
} fuzzy_set;
typedef struct {
fuzzy_set input_set;
double output_value;
} rule;
double membership(double value, fuzzy_set fs) {
if (value <= fs.low) return 0;
if (value >= fs.high) return 1;
return (value - fs.low) / (fs.high - fs.low);
}
double defuzzify(rule rules[], double input, int num_rules) {
double weighted_sum = 0;
double weight_sum = 0;
for (int i = 0; i < num_rules; i++) {
double membership_degree = membership(input, rules[i].input_set);
weighted_sum += membership_degree * rules[i].output_value;
weight_sum += membership_degree;
}
return (weight_sum != 0) ? (weighted_sum / weight_sum) : 0;
}
int main() {
rule rules[] = {
{{0, 5}, 10},
{{3, 7}, 20},
{{6, 10}, 30}
};
int num_rules = sizeof(rules) / sizeof(rules[0]);
double test_input[] = {2.0, 4.0, 6.0, 8.0};
int num_inputs = sizeof(test_input) / sizeof(test_input[0]);
printf("Вхід | Вихід (дефаззифікація)\n");
for (int i = 0; i < num_inputs; i++) {
double output = defuzzify(rules, test_input[i], num_rules);
printf("%.1f | %.2f\n", test_input
[i
], output
); }
return 0;
}
I2luY2x1ZGUgPHN0ZGlvLmg+Cgp0eXBlZGVmIHN0cnVjdCB7CiAgICBkb3VibGUgbG93OwogICAgZG91YmxlIGhpZ2g7Cn0gZnV6enlfc2V0OwoKdHlwZWRlZiBzdHJ1Y3QgewogICAgZnV6enlfc2V0IGlucHV0X3NldDsKICAgIGRvdWJsZSBvdXRwdXRfdmFsdWU7Cn0gcnVsZTsKCmRvdWJsZSBtZW1iZXJzaGlwKGRvdWJsZSB2YWx1ZSwgZnV6enlfc2V0IGZzKSB7CiAgICBpZiAodmFsdWUgPD0gZnMubG93KSByZXR1cm4gMDsKICAgIGlmICh2YWx1ZSA+PSBmcy5oaWdoKSByZXR1cm4gMTsKICAgIHJldHVybiAodmFsdWUgLSBmcy5sb3cpIC8gKGZzLmhpZ2ggLSBmcy5sb3cpOwp9Cgpkb3VibGUgZGVmdXp6aWZ5KHJ1bGUgcnVsZXNbXSwgZG91YmxlIGlucHV0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