How to install Lapack on Mac OS?

This is a question I get asked a lot. Lapack is actually included in Accelerate library provided by Apple. You can include it in the header file of your C++ source code. Refer to this post for more information on how to use Lapack included in Accelerate.

If you like to use the latest version of Lapack, you can easily install it using Homebrew. Enter the following command in a terminal window to install Homebrew:

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

To install Lapack libraries, you should first install GFortran which is included as a part of GCC. Run the following command in a terminal window:

brew install gcc

Now, you can simply install Lapack by typing the following command in a terminal window:

brew install lapack

Please let me know your questions in the comment section.

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

Apple provides Accelerate library which includes 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