Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Updated the product of numbers code so that it handles non-positive n… #29

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 28 additions & 7 deletions src/prod.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
#include "product_log.h"
#include <omp.h>
#include <iostream>
#include <cmath>
using namespace std;
// Function to initialize the array
void initialize_array(int* a, int size, int value) {
Expand All @@ -10,20 +11,37 @@ void initialize_array(int* a, int size, int value) {
}
}

// Function to compute the sum of logarithms in parallel
double compute_log_sum(int* a, int size, int num_threads) {
// Function to compute the sum of logarithms in parallel (HANDLING NEGATIVE VALUES ALSO)
double compute_log_sum(int* a, int size, int num_threads, bool &zero_val, int &neg_vals) {
double log_sum = 0.0;

#pragma omp parallel for default(shared) reduction(+:log_sum) num_threads(num_threads)
for (int i = 0; i < size; i++) {
log_sum += log(a[i]);
if(a[i] == 0){
zero_val = true;
}
else if(a[i] < 0){
neg_vals++;
log_sum += log(abs(a[i]));
}
else{
log_sum += log(a[i]);
}
}

return log_sum;
}

// Function to compute the product using the sum of logarithms
double compute_product(double log_sum) {

double compute_product(double log_sum, bool &zero_val, int &neg_vals) {
// Function to compute the product using the sum of logarithms (Returning 0 if any one input is 0)
if(zero_val){
return 0.0;
}
// If the number of negative values is odd, the product should be negative
else if((neg_vals%2)!=0){
return -1.0*exp(log_sum);
}
return exp(log_sum);
}

Expand All @@ -38,11 +56,14 @@ int main(int argc, char *argv[]) {
// Initialize array
initialize_array(a, ARR_SIZE, 2);

bool zero_val = false; // Initially we don't know if 0 is present in input or no, so we set it to false
int neg_vals = 0; // Initially number of negative values in input be set as 0

// Compute the log sum in parallel
double log_sum = compute_log_sum(a, ARR_SIZE, num_threads);
double log_sum = compute_log_sum(a, ARR_SIZE, num_threads, zero_val, neg_vals);

// Compute the product using the log sum
double prod = compute_product(log_sum);
double prod = compute_product(log_sum, zero_val, neg_vals);

// Print the result
cout << "Product=" << prod << endl;
Expand Down