In: Computer Science
Please implement the 5 questions in source code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main( int argc, char* argv[] )
{
// Size of vectors
int n = 10000;
// Input vectors
double *restrict a;
double *restrict b;
// Output vector
double *restrict c;
// Size, in bytes, of each vector
size_t bytes = n*sizeof(double);
/* Q1: Allocate memory for vector a (10 points)*/
/* Q2: Allocate memory for vector b (10 points)*/
/* Q3: Allocate memory for vector c (10 points)*/
int i;
/* Initialize content of input vectors, vector a[i] = sin(i)^2 vector b[i] = cos(i)^2
*
*
* Q4: Please implement it.(30 points)
*
*
*
*/
#pragma acc kernel copyin(a[0:n],b[0:n]), copyout(c[0:n])
/* sum component wise and save result into vector c
*
*
*
* Q5: Please implement it.(30 points)
*
*
*
*
*/
// Sum up vector c and print result divided by n, this should equal 1 within error
double sum = 0.0;
for(i=0; i<n; i++)
sum += c[i];
sum = sum/n;
printf("final result: %f\n", sum);
// Release memory
free(a);
free(b);
free(c);
return 0;
OUTPUT:
CODE:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(int argc, char* argv[])
{
// Size of vectors
int n = 10000;
// Input vectors
double* a = NULL;
double* b = NULL;
// Output vector
double* c = NULL;
// Size, in bytes, of each vector
size_t bytes = n * sizeof(double);
/* Q1: Allocate memory for vector a (10
points)*/
a = (double*)malloc(bytes);
/* Q2: Allocate memory for vector b (10
points)*/
b = (double*)malloc(bytes);
/* Q3: Allocate memory for vector c (10
points)*/
c = (double*)malloc(bytes);
int i;
/* Initialize content of input vectors, vector a[i] = sin(i)^2 vector b[i] = cos(i)^2
*
*
* Q4: Please implement it.(30 points)
*
*
*
*/
for (int i = 0;i < 10000;++i)
{
a[i] = pow(sin(i), 2);
b[i] = pow(cos(i), 2);
}
#pragma acc kernel copyin(a[0:n],b[0:n]), copyout(c[0:n])
/* sum component wise and save result into vector c
*
*
*
* Q5: Please implement it.(30 points)
*
*
*
*
*/
for (int i = 0;i < 10000;++i)
{
c[i] = a[i] + b[i];
}
// Sum up vector c and print result divided by n, this
should equal 1 within error
double sum = 0.0;
for (i = 0; i < n; i++)
sum += c[i];
sum = sum / n;
printf("final result: %f\n", sum);
// Release memory
free(a);
free(b);
free(c);
return 0;
}