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

Fix Issue #9: Add partial pivoting to LU Factorization #28

Merged
merged 1 commit into from
Dec 2, 2024
Merged
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
38 changes: 34 additions & 4 deletions src/LU_factorisation.cpp
Original file line number Diff line number Diff line change
@@ -1,17 +1,24 @@
// lu_decomposition.cpp
#include "lu_decomposition.h"
#include "../include/lu_decomposition.h"
#include <omp.h>
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>

using namespace std;
// LU Decomposition function
void l_u_d(float** a, float** l, float** u, int size)
void l_u_d(float** a, float** l, float** u, int* p , int size) // Added pivot array p
{
// Initialize a simple lock for parallel region
omp_lock_t lock;
omp_init_lock(&lock);

// Initialize permutation array p
for(int i = 0 ; i < size ; i++){
p[i] = i ;
}

// Initialize L and U matrices
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
Expand All @@ -29,9 +36,30 @@ void l_u_d(float** a, float** l, float** u, int size)
}

// Parallelize the LU decomposition
#pragma omp parallel shared(a, l, u)
#pragma omp parallel shared(a, l, u , p) // Add p to shared
{
for (int k = 0; k < size; k++) {
// Find pivot row
int pivot = k ;
float max_val = fabs(a[k][k]) ;
for(int i = k+1 ; i < size ; i++){
if(fabs(a[i][k] > max_val)){
pivot = i ;
max_val = fabs(a[i][k]) ;
}
}

// Row swapping
if(pivot != k){
omp_set_lock(&lock) ;
swap(p[k] , pivot) ; // Swapping in permutation array
for(int j = 0 ; j < size ; j++){
if(j < k) swap(a[k][j] , l[pivot][j]) ;
}
omp_unset_lock(&lock);
}


// Update U matrix
#pragma omp for schedule(static)
for (int j = k; j < size; j++) {
Expand Down Expand Up @@ -62,11 +90,13 @@ void l_u_d(float** a, float** l, float** u, int size)
int main(int argc, char *argv[]) {
int size = 2;
float **a, **l, **u;
int *p ; // Added permutation array

// Allocate memory for the 2D arrays
a = (float **)malloc(size * sizeof(float *));
l = (float **)malloc(size * sizeof(float *));
u = (float **)malloc(size * sizeof(float *));
p = (int *)malloc(size * sizeof(int)); // Allocated memory for pivot array
for (int i = 0; i < size; i++) {
a[i] = (float *)malloc(size * sizeof(float));
l[i] = (float *)malloc(size * sizeof(float));
Expand All @@ -85,7 +115,7 @@ int main(int argc, char *argv[]) {
}

// Perform LU decomposition
l_u_d(a, l, u, size);
l_u_d(a , l , u , p , size) ; // Passed pivot array

// Print L matrix
printf("L Matrix:\n");
Expand Down