Click here to Skip to main content
15,891,136 members
Articles / Programming Languages / C++
Tip/Trick

Mean Absolute Error Code in C++

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
7 Apr 2023CPOL1 min read 5.1K   1  
Mean absolute error calculation in C++
This tip uses an example code to show how to calculate mean absolute error (MAE) in C++.

Introduction

In statistics, mean absolute error (MAE) is a measure of errors between paired observations expressing the same phenomenon. Examples of Y versus X include comparisons of predicted versus observed, subsequent time versus initial time, and one technique of measurement versus an alternative technique of measurement

Using the Code

Here's an example code for calculating mean absolute error (MAE) in C++:

C++
#include <iostream>
#include <vector>
#include <cmath>

double mae(const std::vector<double>& predictions, const std::vector<double>& targets)
{
    if (predictions.size() != targets.size()) {
        throw std::invalid_argument("Size of predictions and targets do not match.");
    }

    double sum = 0;
    for (size_t i = 0; i < predictions.size(); i++) {
        sum += std::abs(predictions[i] - targets[i]);
    }

    return sum / predictions.size();
}

int main()
{
    std::vector<double> predictions = {1.2, 3.4, 2.1, 5.6, 4.3};
    std::vector<double> targets = {1.5, 2.9, 2.0, 6.1, 3.8};

    try 
    {
        double mae_val = mae(predictions, targets);
        std::cout << "MAE: " << mae_val << std::endl;
    }
    catch (const std::invalid_argument& e) {
        std::cerr << e.what() << std::endl;
    }

    return 0;
}

Points of Interest

In this example, the mae() function takes in two vectors of doubles predictions and targets, and calculates the MAE between them. It first checks if the two vectors are of the same size, and throws an exception if they are not.

Then, it iterates over each element of the vectors and calculates the absolute difference between the corresponding elements of predictions and targets. The absolute differences are summed up and divided by the size of the vectors to get the mean absolute error, which is then returned.

Finally, in the main() function, we create two example vectors predictions and targets, call the mae() function on them, and print out the result. If an exception is thrown due to the vectors not being of the same size, we catch it and print out the error message.

History

  • 7th April, 2023: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Iran (Islamic Republic of) Iran (Islamic Republic of)
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --