Write a solver for systems of equations by using Lapack on Mac OS

Apple provides the Accelerate library which includes the linear algebra library (Lapack). In this post, we will go through writing a simple C++ program to use this library on Mac OS.

Let’s solve the following equations:

We can rewrite the equations as:

Now, let’s write our code:

#include <iostream>
#include <Accelerate/Accelerate.h>

int main()
{
int number_of_rows = 2;
int number_of_cols = 2;
int number_of_right_hand_side_cols = 1;
int LDA = 2;
int LDB = 2;
int IPIV[3];
int INFO=10;
char TRANS = 'N'; // Non transpose

double a[2*2] = {2, 1, 
		1, -1};
double b[2] = {0,
	      0};

dgetrf_(&number_of_rows, &number_of_cols, a, &LDA, IPIV, &INFO);
if (!INFO)
	std::cout << "LU factorization executed without errors." << std::endl;

dgetrs_(&TRANS, &number_of_rows, &number_of_right_hand_side_cols, 
		a, &LDA, IPIV, b, &LDB, &INFO);

std::cout << "Result: x_0 = "<< *b <<", x_1 = "<<*(b+1) << std::endl;

if (!INFO)
	std::cout << "Solver executed without errors." << std::endl;

return(0);
}

Now, run the code by using the following commands in a terminal:

g++ -llapack lapack_test.cpp -o ltest.o
./ltest.o


Spread the love

Leave a Reply