40,182 views
17 votes
17 votes
Modify the statistics program from this chapter so that client programshave more flexibility in computing the mean and/ or standard deviation.Specifically, redesign the library to have the following functions:mean(nums) Returns the mean of numbers in nums.stdDev(nums) Returns the standard deviation of nums.meanStdDev (nums) Returns both the mean and standard deviation of nums.

User Zheng Qu
by
3.1k points

1 Answer

16 votes
16 votes

Answer and Explanation:

Using Javascript:

function mean(nums){

var array_numbers= new array(nums);

var meanofNums= array_numbers.reduce()/array_numbers.length;

Console.log(meanofNums);

}

Function Std(nums){

var OurArray= new Array(nums);

var meanOfnums= mean(nums);

var i;

for(i=0; i<=OurArray.length; i++){

OurArray[i]= OurArray[i]-meanOfnums*OurArray[i]-meanOfnums;

}

var al_stdOfnums= OurArray.reduce()/OurArray.length;

var stdOfnums= Math. sqrt(al_stdOfnums);

Console.log(stdOfnums);

}

function meanStdDev (nums){

mean(nums);

Std(nums);

}

/*From the code above, we have defined functions and used them in the last function definition meanStdDev (nums), making for code reusability. In defining the functions, we have followed the formulas for calculating mean and standard deviations and implemented in that order. Notice how we used a for loop in std(nums) function definition to iterate through the elements of the array nums, squaring each value and reassigning a new value for each element(using index value) in the array. We then added these values in array using reduce method, dividing by array length and square rooting the value using the math object method sqrt().*/

User Heitortsergent
by
3.1k points