Write a Solver for Systems of Equations 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.
The Equations¶
Let’s solve the following equations:
We can rewrite the equations as:
The Code¶
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);
}
Compile and Run¶
Now, run the code by using the following commands in a terminal:
#!/bin/bash
g++ -llapack lapack_test.cpp -o ltest.o
./ltest.o