Hello coders, today we are going to solve Day 1: Standard Deviation HackerRank Solution which is a part of 10 Days of Statistics Series.
Objective
In this challenge, we practice calculating standard deviation.
Task
Given an array, arr, of n integers, calculate and print the standard deviation. Your answer should be in decimal form, rounded to a scale of 1 decimal place (i.e., 12.3 format). An error margin of +0.1 will be tolerated for the standard deviation.
Example
arr = [2, 5, 2, 7, 4]
The sum of the array values is 20 and there are 5 elements. The mean is 4.0.
Subtract the mean from each element, square each result, and take their sum.
Their sum is 18. Take the square root of 18/5 to get 1.7, the standard deviation.
Function Description
Complete the stdDev function in the editor below.
stdDev has the following parameters:
– int arr[n]: an array of integers
Prints
– float: the standard deviation to 1 place after the decimal
Input Format
The first line contains an integer, n, denoting the size of arr.
The second line contains n space-separated integers that describe arr.
Constraints
- 5 <= n <= 100
- 0 < arr[i] <= 105
Output Format
Print the standard deviation on a new line, rounded to a scale of 1 decimal place (i.e., 12.3 format).
Sample Input
STDIN Function
----- --------
5 arr[] size n = 5
10 40 30 50 20 arr =[10, 40, 30, 50, 20]
Sample Output
14.1
Solution – Day 1: Standard Deviation Solution
C++
#include <cmath> #include <cstdio> #include <vector> #include <iostream> #include <algorithm> using namespace std; int main() { /* Enter your code here. Read input from STDIN. Print output to STDOUT */ int n; cin>>n; int a[n+4]; double sum=0, sum1=0; for(auto i=0; i<n; i++) { cin>>a[i]; sum += a[i]; } double mean = (double)(sum/n); for(auto i=0; i<n; i++) { sum1 += (((double)a[i]-mean)*((double)a[i]-mean)); } double std = (double)sqrt(sum1/n); printf("%.1f\n", std); return 0; }
Python
import math # Define functionts def mean(data): return sum(data) / len(data) def stddev(data, size): sum = 0 for i in range(size): sum = sum + (data[i] - mean(data)) ** 2 return math.sqrt(sum / size) # Set data size = int(input()) numbers = list(map(int, input().split())) # Get standard deviation print(round(stddev(numbers, size), 1))
Disclaimer: The above Problem (Standard Deviation) is generated by Hacker Rank but the Solution is Provided by CodingBroz. This tutorial is only for Educational and Learning Purpose.