Program Plan:
- In function “meanIterative()”:
- Compute sum of array elements using a “for” loop.
- Compute mean by dividing sum with number of elements in array.
- In function “varianceIterative()”:
- Compute sum of square of difference between each element with mean.
- Compute variance by dividing it with “n-1”.
- In function “meanRecursive()”:
- If starting index “ii” is same as “n-1”, return element divided by “n”.
- Otherwise, increment the value “ii” by “1” and compute mean all numbers in array by calling function recursively.
- In function “varianceRecursive()”:
- If starting index “ii” is same as “n-1”, return variance of that element.
- Otherwise, increment the value “ii” by “1” and compute variance all numbers in array by calling function recursively.
- In “main()” function:
- Create random input arrays of size “500”, “1000”, “1500” and “2000”.
- For each input array compute standard deviation by using both iterative and recursive functions.
- Compute running time for both and compare each other.
/**********************************************************
* Program to compare running time to compute standard *
* deviation of different sized samples using iterative *
* and recursive functions. *
**********************************************************/
Explanation of Solution
Program:
//Include header files
#include<iostream>
#include<ctime>
using namespace std;
//Iterative function to compute mean of n numbers
double meanIterative(int data[], int n)
{
//Declare variable
double mean;
//Initialize summ as 0
int summ=0;
//Each number from array
for (int i = 0; i < n; i++)
{
//Add number with summ
summ = summ + data[i];
}
//Compute mean of numbers
mean =(double) summ / (double)n;
//Return mean
return mean;
}
//Iterative function to compute variance of n numbers
double varianceIterative(int data[], int n, double mean)
{
//Declare variable
double varianc;
//Initialize summm as 0
double summm=0;
//Each number from array
for (int i = 0; i < n; i++)
{
//Add number with summm
summm = summm + pow((data[i] - mean), 2);
}
//Compute variance
varianc = summm / (float)(n-1);
//Return variance
return varianc;
}
//Recursive function to compute mean of n numbers
double meanRecursive(int data[], int ii,int n)
{
//If starting index ii is equal to n
if (ii == n-1)
//Return mean of that number
return (double)data[ii]/(double)n;
/*Otherwise increment value of ii by 1 and compute mean of numbers by calling function itself recursively*/
return (double)data[ii]/(double)n +meanRecursive(data, ii + 1, n);
}
//Recursive function to compute variance of n numbers
double varianceRecursive(int data[], int ii,int n, double mean)
{
//If starting index ii is equal to n
if (ii == n-1)
//Return variance of that number
return pow((double)data[ii]-mean,2)/(double)(n-1);
/*Otherwise increment value of ii by 1 and compute variance of numbers by calling function itself recursively*/
return pow((double)data[ii]-mean,2)/(double)(n-1) +varianceRecursive(data, ii + 1, n, mean);
}
//Program begins with main() function
int main()
{
//Declare variables
int data_500_S[500],data_1000_S[1000],data_1500_S[1500],data_2000_S[2000];
srand((unsigned)time(0));
//For each index of array of size 500
for(int ii=0;ii<500;ii++)
{
/*Compute random number and store it into array index*/
data_500_S[ii] = rand() % 10000;
}
//For each index of array of size 1000
for(int ii=0;ii<1000;ii++)
{
/*Compute random number and store it into array index*/
data_1000_S[ii] = rand() % 10000;
}
for(int ii=0;ii<1500;ii++)
{
/*Compute random number and store it into array index*/
data_1500_S[ii] = rand() % 10000;
}
for(int ii=0;ii<2000;ii++)
{
/*Compute random number and store it into array index*/
data_2000_S[ii] = rand() % 10000;
}
//Declare variables
double meeanIte, varianceIte,standarddevIte,meeanRec, varianceRecu,standarddevRecu ;
//For array input of size 500
cout<<"For n=500: \n"<<endl;
//Capture current time and store it as initial time
double start_s=clock();
/*Call iterative function to compute mean of array elements*/
meeanIte=meanIterative(data_500_S, 500);
cout<<"Mean using Iterative function is: "<<meeanIte<<endl;
/*Call iterative function to compute variance of array elements*/
varianceIte=varianceIterative(data_500_S, 500,meeanIte);
cout<<"Variance using Iterative function is: "<<varianceIte<<endl;
//Compute standard deviation using iterative functions
standarddevIte=sqrt(varianceIte);
cout<<"Standard deviation using Iterative function is: "<<standarddevIte<<endl;
//Capture current time and store it as stop time
double stop_s=clock();
//Compute running time in by using start and end time
cout << "Running time for iterative function: " << (stop_s-start_s)/double(CLOCKS_PER_SEC) *1000<< " Milli seconds"<<endl;
//Capture current time and store it as initial time
start_s=clock();
/*Call recursive function to find mean of array elements*/
meeanRec=meanRecursive(data_500_S, 0,500);
cout<<"\n Mean using Recursive function is: "<<meeanRec<<endl;
/*Call recursive function to find variance of array elements*/
varianceRecu=varianceRecursive(data_500_S, 0,500,meeanRec);
cout<<"Variation using Recursive function is: "<<varianceRecu<<endl;
//Compute standard deviation using recursive functions
standarddevRecu=sqrt(varianceRecu);
cout<<"Standard deviation using Recursive function is: "<<standarddevRecu<<endl;
//Capture current time and store it as stop time
stop_s=clock();
cout << "Running time for Recursive function: " << (stop_s-start_s)/double(CLOCKS_PER_SEC)*1000<< " Milli seconds"<<endl;
//For array input of size 1000
cout<<"\n For n=1000: \n"<<endl;
//Capture current time and store it as initial time
start_s=clock();
/*Call iterative function to compute mean of array elements*/
meeanIte=meanIterative(data_1000_S, 1000);
cout<<"Mean using Iterative function is: "<<meeanIte<<endl;
/*Call iterative function to compute variance of array elements*/
varianceIte=varianceIterative(data_1000_S, 1000,meeanIte);
cout<<"Variance using Iterative function is: "<<varianceIte<<endl;
//Compute standard deviation using iterative functions
standarddevIte=sqrt(varianceIte);
cout<<"Standard deviation using Iterative function is: "<<standarddevIte<<endl;
//Capture current time and store it as stop time
stop_s=clock();
//Compute ruuning time in by using start and end time
cout << "Running time for iterative function: " << (stop_s-start_s)/double(CLOCKS_PER_SEC)*1000<< " Milli seconds"<<endl;
//Capture current time and store it as initial time
start_s=clock();
/*Call recursive function to find mean of array elements*/
meeanRec=meanRecursive(data_1000_S, 0,1000);
cout<<"\n Mean using Recursive function is: "<<meeanRec<<endl;
/*Call recursive function to find variance of array elements*/
varianceRecu=varianceRecursive(data_1000_S, 0,1000,meeanRec);
cout<<"Variation using Recursive function is: "<<varianceRecu<<endl;
//Compute standard deviation using recursive functions
standarddevRecu=sqrt(varianceRecu);
cout<<"Standard deviation using Recursive function is: "<<standarddevRecu<<endl;
//Capture current time and store it as stop time
stop_s=clock();
//Compute running time in by using start and end time
cout << "Running time for Recursive function: " << (stop_s-start_s)/double(CLOCKS_PER_SEC) *1000<< " Milli seconds"<<endl;
//For array input of size 500
cout<<"\n For n=1500: \n"<<endl;
//Capture current time and store it as start time
start_s=clock();
/*Call iterative function to compute mean of array elements*/
meeanIte=meanIterative(data_1500_S, 1500);
cout<<"Mean using Iterative function is: "<<meeanIte<<endl;
/*Call iterative function to compute variance of array elements*/
varianceIte=varianceIterative(data_1500_S, 1500,meeanIte);
cout<<"Variance using Iterative function is: "<<varianceIte<<endl;
//Compute standard deviation using iterative functions
standarddevIte=sqrt(varianceIte);
cout<<"Standard deviation using Iterative function is: "<<standarddevIte<<endl;
//Capture current time and store it as stop time
stop_s=clock();
//Compute running time in by using start and end time
cout << "Running time for iterative function: " << (stop_s-start_s)/double(CLOCKS_PER_SEC)*1000 << " Milli seconds"<<endl;
//Capture current time and store it as start time
start_s=clock();
/*Call recursive function to find mean of array elements*/
meeanRec=meanRecursive(data_1500_S, 0,1500);
cout<<"\n Mean using Recursive function is: "<<meeanRec<<endl;
/*Call recursive function to find variance of array elements*/
varianceRecu=varianceRecursive(data_1500_S, 0,1500,meeanRec);
cout<<"Variation using Recursive function is: "<<varianceRecu<<endl;
//Compute standard deviation using recursive functions
standarddevRecu=sqrt(varianceRecu);
cout<<"Standard deviation using Recursive function is: "<<standarddevRecu<<endl;
//Capture current time and store it as stop time
stop_s=clock();
//Compute running time in by using start and end time
cout << "Running time for Recursive function: " << (stop_s-start_s)/double(CLOCKS_PER_SEC)*1000<< " Milli seconds"<<endl;
//For array input of size 500
cout<<"\n For n=2000: \n"<<endl;
//Capture current time and store it as start time
start_s=clock();
/*Call iterative function to compute mean of array elements*/
meeanIte=meanIterative(data_2000_S, 2000);
cout<<"Mean using Iterative function is: "<<meeanIte<<endl;
/*Call iterative function to compute variance of array elements*/
varianceIte=varianceIterative(data_2000_S, 2000,meeanIte);
cout<<"Variance using Iterative function is: "<<varianceIte<<endl;
//Compute standard deviation using iterative functions
standarddevIte=sqrt(varianceIte);
cout<<"Standard deviation using Iterative function is: "<<standarddevIte<<endl;
//Capture current time and store it as stop time
stop_s=clock();
//Compute running time in by using start and end time
cout << "Running time for iterative function: " << (stop_s-start_s)/double(CLOCKS_PER_SEC) *1000<< " Milli Seconds"<<endl;
//Capture current time and store it as start time
start_s=clock();
/*Call recursive function to find mean of array elements*/
meeanRec=meanRecursive(data_2000_S, 0,2000);
cout<<"\n Mean using Recursive function is: "<<meeanRec<<endl;
/*Call recursive function to find variance of array elements*/
varianceRecu=varianceRecursive(data_2000_S, 0,2000,meeanRec);
cout<<"Variation using Recursive function is: "<<varianceRecu<<endl;
//Compute standard deviation using recursive functions
standarddevRecu=sqrt(varianceRecu);
cout<<"Standard deviation using Recursive function is: "<<standarddevRecu<<endl;
//Capture current time and store it as stop time
stop_s=clock();
//Compute running time in by using start and end time
cout << "Running time for Recursive function: " << (stop_s-start_s)/double(CLOCKS_PER_SEC)*1000<< " Milli Seconds"<<endl;
//Return from program
system("pause");
return 0;
}
Comparison:
Input array size, n | Running time in Milliseconds | |
Iterative Method | Recursive method | |
500 | 17 | 14 |
1000 | 9 | 6 |
1500 | 7 | 7 |
2000 | 7 | 7 |
Conclusion:
- Running time for input array of size “n” equals “500” is larger for iterative method than recursive method.
- For other input arrays the running time for both iterative and recursive are almost similar or sometimes it varies for small values.
Output:
For n=500:
Mean using Iterative function is: 4394.44
Variance using Iterative function is: 8.22268e+006
Standard deviation using Iterative function is: 2867.52
Running time for iterative function: 17 Milli seconds
Mean using Recursive function is: 4394.44
Variation using Recursive function is: 8.22268e+006
Standard deviation using Recursive function is: 2867.52
Running time for Recursive function: 14 Milli seconds
For n=1000:
Mean using Iterative function is: 4908.97
Variance using Iterative function is: 8.77065e+006
Standard deviation using Iterative function is: 2961.53
Running time for iterative function: 9 Milli seconds
Mean using Recursive function is: 4908.97
Variation using Recursive function is: 8.77065e+006
Standard deviation using Recursive function is: 2961.53
Running time for Recursive function: 6 Milli seconds
For n=1500:
Mean using Iterative function is: 4531.62
Variance using Iterative function is: 8.7867e+006
Standard deviation using Iterative function is: 2964.24
Running time for iterative function: 7 Milli seconds
Mean using Recursive function is: 4531.62
Variation using Recursive function is: 8.7867e+006
Standard deviation using Recursive function is: 2964.24
Running time for Recursive function: 7 Milli seconds
For n=2000:
Mean using Iterative function is: 4641.43
Variance using Iterative function is: 8.57314e+006
Standard deviation using Iterative function is: 2927.99
Running time for iterative function: 7 Milli Seconds
Mean using Recursive function is: 4641.43
Variation using Recursive function is: 8.57314e+006
Standard deviation using Recursive function is: 2927.99
Running time for Recursive function: 7 Milli Seconds
Want to see more full solutions like this?
Chapter 5 Solutions
EBK DATA STRUCTURES AND ALGORITHMS IN C
- The three integers n, I and j, with I and j being between 1 and 2n, are the prerequisites to the issue. You have a board of squares that is 2n by 2n squares. Each tile has an adequate amount of pieces and the desired form. With the exception of the solitary square at position I j, you must cover every 2n 2n tile on the board by placing nonoverlapping tiles. Provide a recursive method for this issue where you lay one tile on your own and then enlist the aid of four buddies. a case is a phrase, right?arrow_forwardGiven a positive integer 'n', find and return the minimum number of steps that 'n' has to take to get reduced to 1. You can perform any one of the following 3 steps:1.) Subtract 1 from it. (n = n - 1) ,2.) If its divisible by 2, divide by 2.( if n % 2 == 0, then n = n / 2 ) ,3.) If its divisible by 3, divide by 3. (if n % 3 == 0, then n = n / 3 ). Write brute-force recursive solution for this.Input format :The first and the only line of input contains an integer value, 'n'.Output format :Print the minimum number of steps.Constraints :1 <= n <= 200 Time Limit: 1 secSample Input 1 :4Sample Output 1 :2 Explanation of Sample Output 1 :For n = 4Step 1 : n = 4 / 2 = 2Step 2 : n = 2 / 2 = 1 Sample Input 2 :7Sample Output 2 :3Explanation of Sample Output 2 :For n = 7Step 1 : n = 7 - 1 = 6Step 2 : n = 6 / 3 = 2 Step 3 : n = 2 / 2 = 1 SolutionDp///.arrow_forwardAssume that you were given N cents (N is an integer) and you were asked to break up the N cents into coins consisting of 1 cent, 2 cents and 5 cents. Write a dynamicprogramming based recursive algorithm, which returns the smallest (optimal) number of coins needed to solve this problem. For example, if your algorithm is called A, and N = 13, then A(N) = A(13) returns 4, since 5+5+2+1 = 13 used the smallest (optimal) number of coins. In contrast, 5+5+1+1+1 is not an optimal answer.arrow_forward
- You want to design an algorithm, called minMax(A,p,r), that takes an array of integers and indexes of the first and last elements, and returns the minimum and maximum values in that range. Now write the pseudo code of a divide and conquer (and therefore, recursive) algorithm with the same time complexity (Θ(n)). You can assume that p ≤ r. Also, in your code, you can return two numbers by returning a pair, e.g. “return (a, b)”, and can save the output in a similar way, e.g. “(a, b) = minMax(parameters)”. (Short answer please)arrow_forwardWrite a recursive function in f#, named specialSum, that has the followeing signature: int * int -> int, where sum(m,n) = m + (m +1) + (m+2) + ... + (m + (n-1)) + (m+n) for m >= 0 and n >= 0: (Hint use two clauses with (m,0) and (m,n) A PATTERNS.) start code with let rec specialSum (m,n) match m,n with | m,0 -> | m,n - >arrow_forwardModeling the spread of a virus like COVID-19 using recursion. Let N = total population (assumed constant, disregarding deaths, births, immigration, and emigration). S n = number who are susceptible to the disease at time n (n is in weeks). I n = number who are infected (and contagious) at time n. R n = number who are recovered (and not contagiuous) at time n. The total population is divided between these three groups: N = S n + I n + R n There are several hidden assumptions here that may or may not apply to COVID-19, such as a recovered person is assumed to not be able to get the disease a second time, at least within the time window being examined. On week 0 (the start), you assume a certain small number of people have the infection (just to get things going). Everyone else is initially susceptible, and no one is recovered. There are two constants of interest: Let period = time period that it takes for an infected person to recover (recover meaning they become not infectious to…arrow_forward
- The following function f uses recursion: def f(n): if n <= 1 return n else return f(n-1) + f(n-2) Let n be a valid input, i.e., a natural number. Which of the following functions returns the same result but without recursion? a) def f(n): a <- 0 b <- 1 if n = 0 return a elsif n = 1 return b else for i in 1..n c <- a + b a <- b b <- c return b b) def f(n): a <- 0 i <- n while i > 0 a <- a + i + (i-1) return a c) def f(n): arr[0] <- 0 arr[1] <- 1 if n <= 1 return arr[n] else for i in 2..n arr[i] <- arr[i-1] + arr[i-2] return arr[n] d) def f(n): arr[0..n] <- [0, ..., n] if n <= 1 return arr[n] else a <- 0 for i in 0..n a <- a + arr[i] return aarrow_forwardwrite java codes to do the following: Write a recursive function to check if an integer array is negative symmetric, for example, an array of 10, 20, 30, 90, -30, -20, -10 is considered as negative symmetric, while an array of 10, 20, 30, 90, 30, 20, 10 is not considered as negative symmetric. public static boolean checkArraySym(int [ ] A, int first, int last) that receives an array A, first index, last index and checks if the array is negative symmetricarrow_forwardWhich is the base case of the following recursion function: def mult3(n): if n == 1: return 3 else: return mult3(n-1) + 3 else n == 1 mult3(n) return mult3(n-1) + 3arrow_forward
- (a) Give a recursive definition of F(n) where F(n) =1+2+3+....+n. (b) Find the value of a4 if a1 = 1, a2 = 2, and an =an−1 + an−2 +· · ·+a1arrow_forwardInduction and RecursionA number sequence, t(n), where n ≥ 1, is given by the following recursive algorithm, value a = 1, b = 2 Function t(n):1. If n = 1 then1.1. t ← 3b+5else1.2. t ← -n + a∙t(n-1) a) Calculate the first 3 numbers in the number sequence ( t(1), t(2), ...t(3) ). b) For the fifth number t(5) , a call to the function with n=5, make a trace table for the algorithm, thatis calculate and write down a table with the contents of the different variables for every copy of therecursive algorithm, as the computer would go through the algorithm step by step.arrow_forwardBy using java, Write a recursive function that finds the maximum element in an array ofintegers, based on comparing the first element in the array against themaximum in the rest of the array recursively.arrow_forward
- Database System ConceptsComputer ScienceISBN:9780078022159Author:Abraham Silberschatz Professor, Henry F. Korth, S. SudarshanPublisher:McGraw-Hill EducationStarting Out with Python (4th Edition)Computer ScienceISBN:9780134444321Author:Tony GaddisPublisher:PEARSONDigital Fundamentals (11th Edition)Computer ScienceISBN:9780132737968Author:Thomas L. FloydPublisher:PEARSON
- C How to Program (8th Edition)Computer ScienceISBN:9780133976892Author:Paul J. Deitel, Harvey DeitelPublisher:PEARSONDatabase Systems: Design, Implementation, & Manag...Computer ScienceISBN:9781337627900Author:Carlos Coronel, Steven MorrisPublisher:Cengage LearningProgrammable Logic ControllersComputer ScienceISBN:9780073373843Author:Frank D. PetruzellaPublisher:McGraw-Hill Education