4

I've an array of numbers and I need to calculate the Sample Standard Deviation using jq.

Sample Standard Deviation formula (credits): Standard Deviation formula

I've tried splitting the code into multiple pieces (length, mean), but none of my attempts worked because I don't know how to merge all the data into a single sqrt and map operation:

# Example of data input
_data="[73,73,76,77,81,100]"

_length=$(echo "$_data" | jq --raw-output 'length')
_mean=$(echo "$_data" | jq --raw-output 'add/length')

_standard_deviation=$(echo "$_data" \
                      | jq --raw-output \
                           --arg length "$_length" \
                           --arg mean "$_mean" \
                           '') # <- sqrt and map ?

echo "$_standard_deviation" # Should print 10.237187
oguz ismail
  • 1
  • 16
  • 47
  • 69
Carlo Corradini
  • 2,927
  • 2
  • 18
  • 24

1 Answers1

7

This is how you do it:

(add / length) as $mean | (map(. - $mean | . * .) | add) / (length - 1) | sqrt

Online demo

oguz ismail
  • 1
  • 16
  • 47
  • 69