Dart: Calculating Variance and Standard Deviation

Updated: February 14, 2023 By: A Goodman Post a comment

Variance is a statistical measure that quantifies the amount of variability or spread in a set of data. It is calculated as the average of the squared differences from the mean of the data.

Standard deviation is the square root of the variance and is another statistical measure of the amount of variability in a set of data. It tells you how much the data deviates from the mean, on average.

In Dart, you can calculate the variance and standard deviation of a list of numbers like this:

// Kindacode.com
// main.dart
import 'dart:math';

void main() {
  List<double> data = [0.5, 1.1, 3, 4, 5, 10, 11, 9, 7.4, 8.2];

  // Calculate the mean
  double mean = data.reduce((a, b) => a + b) / data.length;

  // Calculate the variance
  double variance = data.map((x) => pow(x - mean, 2)).reduce((a, b) => a + b) /
      (data.length - 1);

  // Calculate the standard deviation
  double standardDeviation = sqrt(variance);

  print('Variance: $variance');
  print('Standard Deviation: $standardDeviation');
}

Output:

Variance: 13.888444444444444
Standard Deviation: 3.7267203335432137

If you want to round the results to 2 decimals numbers, use the toStringFixed() method as follows:

var roundedVariance = variance.toStringAsFixed(2);
var roundedStandardDeviation = standardDeviation.toStringAsFixed(2);

Further reading:

You can also tour around our Flutter topic page or Dart topic page for the most recent tutorials and examples.

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles