Although there is the
Statistics.std function, this post shows how to find the **Standard Deviation** in Julia using custom codes.

## What is Standard Deviation?

The Standard Deviation is a value that shows how much the values deviate from their mean. A low value means less amount of variation or dispersion of sample values, while a high value means the values are spread out over a wider range.

## Julia Codes Standard Deviation

We are going to use the Statistics Package for the mean function. Let us begin with a sample of integers. For proceeding, please ensure we have Julia installed in our system.

1 2 3 4 |
using Statistics # Values don't need to sorted samples = [11, 11, 14, 17, 25, 28, 43, 43] |

Then, we find the mean using the Statistics.mean function.

1 |
samples_mean = mean(samples) |

Next, find the number of values in the sample.

1 |
samples_size = length(samples) |

For each value, we subtract it with the samples_mean and square the difference. The Standard Deviation is relative to the mean of the sample values. Then, we sum up these results.

1 2 |
samples = map(x -> (x - samples_mean)^2, samples) samples_sum = sum(samples) |

Lastly, we find the square root of the sum over samples_size - 1 to find the Standard Deviation in Julia.

1 2 3 |
samples_std = sqrt(samples_sum / (samples_size - 1)) println(samples_std) |

## Create a Standard Deviation Function

To reuse the codes anywhere, we can put them in a function for finding the Standard Deviation of sample values. We name the function my_std. Its definition is as follows. We still need the Statistics Package for the mean function.

1 2 3 4 5 6 7 8 |
function my_std(samples) samples_mean = mean(samples) samples_size = length(samples) samples = map(x -> (x - samples_mean)^2, samples) samples_sum = sum(samples) samples_std = sqrt(samples_sum / (samples_size - 1)) return samples_std end |

The complete Julia codes for finding the Standard Deviation, including the function’s usage, are as follows. Notice the function comes before its usage.

1 2 3 4 5 6 7 8 9 10 11 12 13 |
using Statistics function my_std(samples) samples_mean = mean(samples) samples_size = length(samples) samples = map(x -> (x - samples_mean)^2, samples) samples_sum = sum(samples) samples_std = sqrt(samples_sum / (samples_size - 1)) return samples_std end samples = [11, 11, 14, 17, 25, 28, 43, 43] println(my_std(samples)) |

The codes produce the following output.

1 |
13.234154946306814 |

If we know how to complete the Standard Deviation, creating codes in Julia to find the Standard Deviation comes naturally.