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
  • Write a C++ program to scale and average the values in a two-dimensional array. Write the...

    Write a C++ program to scale and average the values in a two-dimensional array. Write the following functions:           void randomize2DArray(int arr[ROW_SIZE][COL_SIZE]) – places random values between 1 and 100 in a two-dimensional array .           void scale2DArray(int arr[ROW_SIZE][COL_SIZE], double scale) – multiplies every value in the two-dimensional array by scale.           double average2DArray(int arr[ROW_SIZE][COL_SIZE]) – calculates the average value over all elements in the two-dimensional array. Randomize and print the values in the two-dimensional array of size 7 x...

  • 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...

  • 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...

  • 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);...

  • Create a program that creates an array of 500 random numbers between -10 and 10. Write...

    Create a program that creates an array of 500 random numbers between -10 and 10. Write several functions: Function 1 - prints the array with a certain number of elements per line. Prototype: void printArray(int array[], int numElements, int numPerLine, ostream &os) Function 2 prints only the array elements that are evenly divisible by an input number. Prototype: void printDivBy(int array[], int numElements, int numPerLine, int divBy, ostream &os) Function 3 takes the input array and returns the maximum, the...

  • Develop a system flowchart and then write a menu-driven C++ program that uses user-defined functions arrays,...

    Develop a system flowchart and then write a menu-driven C++ program that uses user-defined functions arrays, and a random number generator. Upon program execution, the screen will be cleared and the menu shown below will appear at the top of the screen and centered. The menu items are explained below. Help Smallest Quit H or h ( for Help ) option will invoke a function named help() which will display a help screen. The help screen(s) should guide the user...

  • 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 must execute in C using parallel Programming techniques the following serial program: void producer_consumer(int *buffer,...

    I must execute in C using parallel Programming techniques the following serial program: void producer_consumer(int *buffer, int size, int *vec, int n) {    int i, j;    long long unsigned int sum = 0;    for(i=0;i<n;i++) {        if(i % 2 == 0) {   // PRODUCER            for(j=0;j<size;j++) {                buffer[j] = vec[i] + j*vec[i+1];            }        }        else {   // CONSUMER            for(j=0;j<size;j++) {...

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