|
| 1 | +/** |
| 2 | + * @file gaussian.c |
| 3 | + * @brief Implementation of the Gaussian function. |
| 4 | + * @details |
| 5 | + * This program calculates the value of the Gaussian function for a given |
| 6 | + * mean and standard deviation at a specific value. |
| 7 | + * The function follows the formula: |
| 8 | + * f(value) = (1 / (std_dev * sqrt(2 * pi))) * exp(-((value - mean)^2) / (2 * |
| 9 | + * std_dev^2)) |
| 10 | + * @author Shreya123714 (https://github.com/Shreya123714) |
| 11 | + * |
| 12 | + * Based on: https://en.wikipedia.org/wiki/Fuzzy_set |
| 13 | + */ |
| 14 | + |
| 15 | +#include <assert.h> // for assert |
| 16 | +#include <math.h> // for math functions like exp() and sqrt() |
| 17 | +#include <stdio.h> // for IO operations |
| 18 | + |
| 19 | +/** |
| 20 | + * @brief Computes the Gaussian function value. |
| 21 | + * @param value The input value at which to evaluate the function. |
| 22 | + * @param mean The mean of the distribution. |
| 23 | + * @param std_dev The standard deviation of the distribution. |
| 24 | + * @returns The value of the Gaussian function at value. |
| 25 | + */ |
| 26 | +double gaussian(double value, double mean, double std_dev) |
| 27 | +{ |
| 28 | + // Check for valid std_dev |
| 29 | + assert(std_dev > 0); |
| 30 | + |
| 31 | + double exponent = |
| 32 | + exp(-((value - mean) * (value - mean)) / (2 * std_dev * std_dev)); |
| 33 | + return (1 / (std_dev * sqrt(2 * M_PI))) * exponent; |
| 34 | +} |
| 35 | + |
| 36 | +/** |
| 37 | + * @brief Self-test implementations for the Gaussian function. |
| 38 | + * @returns void |
| 39 | + */ |
| 40 | +static void test_gaussian() |
| 41 | +{ |
| 42 | + // Test cases |
| 43 | + assert(fabs(gaussian(0, 0, 1) - 0.3989422804014337) < |
| 44 | + 1e-9); // Standard normal distribution |
| 45 | + assert(fabs(gaussian(1, 0, 1) - 0.24197072451914337) < 1e-9); |
| 46 | + assert(fabs(gaussian(0, 2, 1) - 0.24197072451914337) < 1e-9); |
| 47 | + assert(fabs(gaussian(2, 2, 1) - 0.3989422804014337) < |
| 48 | + 1e-9); // Should be 0.3989422804014337 |
| 49 | + |
| 50 | + printf("All Gaussian tests have successfully passed!\n"); |
| 51 | +} |
| 52 | + |
| 53 | +/** |
| 54 | + * @brief Main function |
| 55 | + * @returns 0 on exit |
| 56 | + */ |
| 57 | +int main() |
| 58 | +{ |
| 59 | + test_gaussian(); // Run self-test implementations |
| 60 | + return 0; |
| 61 | +} |
0 commit comments