Question

write a small C program including the following C functions/subroutines. Your main routine should use these...

write a small C program including the following C functions/subroutines. Your main routine should use these functions to generate a small-ish array of random values and show that the standard deviation lowers as the array is smoothed.
• void random_array(double* array, int size, double scale); – load an array with random double values scaled by scale (random number generators generate double values between 0 and 1). Note: array should point to memory already allocated. • double sum(double* array, int size); – return the sum of all elements in the array • double stdev(double* array, int size); – calculate the standard deviation of the elements in array • void smooth(double* array, int size, double w); – replace all internal values (not the first or last) with a weighted sum of itself and average of the neighboring elements newvali = oldvali ∗w + (oldvali−1 + oldvali+1)(1−w)/2

Main task is use OpenMP to parallelize code from above instructions that generated a random array and repeatedly smoothed the array to lower the standard deviation.

parallelize each for loop individually, meaning that the code between the functions you wrote is serialized. This should not affect performance in any notable way. (In other words, most of the work here is simply using #pragma omp parallel for Make sure to use default(none) on your parallel sections to ensure that you are not inadvertently sharing data (or assuming that some variable is unique to each thread, for that matter).
Prioritize the use of reductions over critical sections.

use a smoothing algorihtm that smooths into a second array, as this is much easier to parallelize safely than an in-place smoothing. (You can do it with an OpenMP for loop, instead of having to partition it yourself). Also note that some versions of the rand() function are forced to be serial by the operating system. Perhaps you can find a safely parallelizable alternate function?)

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Program Files

pxmain.c

// pxmain.c
#include <stdio.h>
#include <stdlib.h>
#include <omp.h>
#include "pxarray.h"
int main()
{
// constants
long ARRAYLENGTH;
int NUMSMOOTH;
double SMOOTHWEIGHT, ARRAYSCALE;

//read input for the above
printf("Enter the length of your array: \n");
scanf("%li", &ARRAYLENGTH);
printf("Enter the max possible value of an element in your array:\n");
scanf("%lf", &ARRAYSCALE);
printf("Enter the weight of your smoothing algorithm [e.g. 0.25]:\n");
scanf("%lf", &SMOOTHWEIGHT);
printf("Enter the number of times you would like to smooth your array:\n");
scanf("%i", &NUMSMOOTH);
printf("\n");

// create an array d[] and initialize it
// demonstration of random_array()
double *d;
d = (double *)malloc(sizeof(double)*ARRAYLENGTH);
random_array(d,ARRAYLENGTH,ARRAYSCALE);

// // // //
// uncomment the below to print the array
// ...leaving it out for large sizes
// // // //

//printf("Hello! Here's your array: \n");
//printarray(d,ARRAYLENGTH);

// demonstration of sum()
printf("The sum of your array is: ");
double start_a = omp_get_wtime();
printf("%f", sum(d,ARRAYLENGTH));
double end_a = omp_get_wtime();
printf("\n");

// demonstration of stdev()
printf("The standard deviation of your array is:");
double start_b = omp_get_wtime();
printf("%f", stdev(d,ARRAYLENGTH));
double end_b = omp_get_wtime();
printf("\n");

// demonstration of smooth()
printf("If we smooth out your array, weighted at ");
printf("%f", SMOOTHWEIGHT);
printf(", we get: \n");

double start_c = omp_get_wtime();
for (int i = 0; i < NUMSMOOTH; i++) {
printf("*** Iteration %d *** \n", i + 1);
smooth(d,ARRAYLENGTH,SMOOTHWEIGHT);
//printarray(d,ARRAYLENGTH);
printf("The stdev of your array after smoothing is: ");
printf("%f \n", stdev(d,ARRAYLENGTH));
}
double end_c = omp_get_wtime();

printf("The runtime of this algorithm was %lf seconds in total.\n",(end_a - start_a) + (end_b - start_b) + (end_c - start_c));
printf("The summation took %lf seconds. \n", end_a - start_a);
printf("The standard deviation took %lf seconds. \n", end_b - start_b);
printf("The smoothing took %lf seconds (totaled over %d iterations). \n", end_c - start_c, NUMSMOOTH);

printf("\n");

return 0;
}

pxarray.h

// pxarray.h
#ifndef PXARRAY_H
#define PXARRAY_H
void printarray(double* array, int size);
void random_array(double* array, int size, double scale);
double sum(double* array, int size);
double stdev(double* array, int size);
void smooth(double* array, int size, double w);
#endif

pxarray.c

// pxarray.c
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <omp.h>
#include "pxarray.h"

// printarray()
// print out the elements of an array
void printarray(double* array, int size) {
#pragma omp for
for (int i = 0; i < size; i++) {
printf("%f \n", array[i]);
}
}

// random_array()
// throws random numbers into the provided array, weighted by scale
void random_array(double* array, int size, double scale) {
//#pragma omp parallel default(none) shared(array, size, scale)
{
//srand(time(0)) ^ omp_get_thread_num();
//srand(time(omp_get_thread_num()));
//#pragma omp for
for (int i = 0; i < size; i++) {
array[i] = rand() * scale / RAND_MAX;
}
}
}

// sum()
// return the sum of all elements in the array
double sum(double* array, int size) {
double sum = 0.0;

#pragma omp parallel for reduction(+:sum) schedule(guided)
for (int i = 0; i < size; i++) {
sum += array[i];
}

return sum;
}

// stdev()
// calculate the standard deviation of the elements in array
double stdev(double* array, int size) {
double stdv = 0.0;
double mean = sum(array, size)/size;

#pragma omp parallel for reduction(+:stdv) schedule(guided)
for (int i = 0; i < size; i++) {
stdv += pow(array[i] - mean, 2);
}

return sqrt(stdv/size);
}

// smooth()
// replace all internal values (not the first or last) with a weighted sum of
// itself and average of the neighboring elements
// newvali = oldvali ∗ w + (oldvali−1 + oldvali+1)(1 − w)/2
void smooth(double* array, int size, double w) {
double temp[size];

//init the "inner" array
temp[0] = array[0];
temp[size - 1] = array[size - 1];

//...and then smooth the array as described above
for (int i = 1; i < size - 1; i++) {
temp[i] = array[i] * w + (array[i - 1] + array[i + 1]) * (1 - w)/2;
}

//finally, replace the elements of array with that of temp
#pragma omp parallel for
for (int i = 0; i < size; i++) {
array[i] = temp[i];
}
}

Hope this helps!

Please let me know if any changes needed.

Thank you!

Add a comment
Know the answer?
Add Answer to:
write a small C program including the following C functions/subroutines. Your main routine should use these...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • c++ I have to write the following functions that I will later use for testt but...

    c++ I have to write the following functions that I will later use for testt but you just have to write the following functions again I have written the interface of it and please make sure it works. will have an array of randomly generated numbers - An array that is already sorted in ascending order - An array that is sorted in reverse (descending) order - An array that is sorted except for the last 10 numbers which are...

  • Fix this C++ code so that the function prototypes come before main. Main needs to be...

    Fix this C++ code so that the function prototypes come before main. Main needs to be declared first. Then call to the functions from inside of main. #include<cstdlib> using namespace std; //prompt user for input void getGrades(int gradeArray[],int size) { for(int i=0; i<size; i++) { cout<<"Enter the grade "<<i+1<<": "; cin>>gradeArray[i]; } } // finding average of all numbers in array float computeAverage(int numbers[],int size) { float sum=0; for(int i=0; i<size; i++) { sum = sum + numbers[i]; //compute sum...

  • C Programming write two functions, similar to what you see in the sample program. The first will ask the user to enter some information (I have included the type in parentheses) First Name (char[]) L...

    C Programming write two functions, similar to what you see in the sample program. The first will ask the user to enter some information (I have included the type in parentheses) First Name (char[]) Last Name (char[]) Age (int) Height in Inches (double) Weight in Pounds (double) You will use pass-by-reference to modify the values of the arguments passed in from the main(). Remember that arrays require no special notation, as they are passed by reference automatically, but the other...

  • Write a C++ program that simulates a lottery game. Your program should use functions and arrays....

    Write a C++ program that simulates a lottery game. Your program should use functions and arrays. Define two global constants: - ARRAY_SIZE that stores the number of drawn numbers (for example 5) -MAX_RANGE that stores the highest value of the numbers ( for example 9 ) The program will use an array of five integers named lottery, and should generate a random number in the range of 0 through 9 for each element of the array. The user should enter...

  • I need a c++ code please. 32. Program. Write a program that creates an integer constant...

    I need a c++ code please. 32. Program. Write a program that creates an integer constant called SIZE and initialize to the size of the array you will be creating. Use this constant throughout your functions you will implement for the next parts and your main program. Also, in your main program create an integer array called numbers and initialize it with the following values (Please see demo program below): 68, 100, 43, 58, 76, 72, 46, 55, 92, 94,...

  • 2. Write a C++ program, that generates a set of random integers and places them in...

    2. Write a C++ program, that generates a set of random integers and places them in an array. The number of values generated and their range are entered by the user. The program then continually prompts the user for one of the following character commands: a: display all the values I: display the values less than a given value g display the values greater than a given value e: display all odd values o: display all even values q: quit...

  • C++ Write a program to compute the mean, median, mode, and sample standard deviation. Output results...

    C++ Write a program to compute the mean, median, mode, and sample standard deviation. Output results to output file and screen. Steps: 1. Populate an array of 99 integers (1-9 inclusively) which are generated randomly. 2. Compute mean, median, mode(with histogram) and sample standard deviation. Use similar functions: void populater (int [], int); double mean (const int [], int, ofstream&); void mode (int [], const int [], int, ofstream&); void median (int [], int, ofstream&); void sort (int [], int);...

  • Write a program that compares the execution speed of two different sorting algorithms: bubble sort and...

    Write a program that compares the execution speed of two different sorting algorithms: bubble sort and selection sort. It should do this via functions you must write with the following prototypes: void setRandomValues(int[], int[], int length); This function sets two integer arrays with identical random values. The first two arguments are two integer arrays of the same length, and the third argument is the length of those arrays. The function then sets each element in the first and second argument...

  • Hi. Could you help me write the below program? Please don't use any header other than...

    Hi. Could you help me write the below program? Please don't use any header other than iostream, no Chegg class, no argc/argv. Nothing too advanced. Thank you! For this assignment you are implement a program that can be used to compute the variance and standard deviation of a set of values. In addition your solution should use the functions specified below that you must also implement. These functions should be used wherever appropriate in your solution. With the exception of...

  • C++ Program Int Main First Please Write one program that does the following: 1.       1.   Ask the...

    C++ Program Int Main First Please Write one program that does the following: 1.       1.   Ask the user for ten (10) grades, and store the data in an array.  Compute the average of all the grades.  Print the original ten grades and the average. a.       Declare an integer array with the name of “grades” of size 10 in the main function. b.      Create a function called “getGrades” that prompts the User for the grades and puts them in an integer array.                                                                i.      The function will receive...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT