-
Notifications
You must be signed in to change notification settings - Fork 5
Examples
njpipeorgan edited this page Aug 10, 2018
·
11 revisions
- Sum of an array
- Sort an array
- Throw exceptions
- Generate an array of random numbers
- Transpose a matrix
- Generate a sparse identity matrix
- Initialize tensor / sparse array
C++
#include <numeric>
#include "wll_interface.h"
double sum(const wll::list<double>& a)
{
return std::accumulate(a.begin(), a.end(), 0.0);
}
DEFINE_WLL_FUNCTION(sum)Mathematica
sum = LibraryFunctionLoad[(*libpath*), "wll_sum", {{Real, 1, "Constant"}}, Real];C++
#include <algorithm>
#include "wll_interface.h"
wll::list<double> sort(wll::list<double> a)
{
std::sort(a.begin(), a.end());
return a;
}
DEFINE_WLL_FUNCTION(sort)Mathematica
sort = LibraryFunctionLoad[(*libpath*),"wll_sort", {{Real, 1}}, {Real, 1}];C++
#include "wll_interface.h"
int int_div(int x, int y)
{
if (y == 0)
throw wll::library_numerical_error("divide by zero");
return x / y;
}
DEFINE_WLL_FUNCTION(int_div)Mathematica
intdiv = LibraryFunctionLoad[(*libpath*), "wll_int_div", {Integer, Integer}, Integer];
exception = LibraryFunctionLoad[(*libpath*), "wll_exception_msg", {}, "UTF8String"];Try dividing by zero:
intdiv[12, 0] (* 12/0 *)
exception[] (* show the recent exception*)C++
#include <random>
#include "wll_interface.h"
wll::list<int> uniform_rand(wll::list<int> range, size_t size)
{
static std::default_random_engine e(std::random_device{}());
std::uniform_int_distribution<int> dist(range(0), range(1));
wll::list<int> result({size});
for (int& element : result)
element = dist(e);
return result;
}
DEFINE_WLL_FUNCTION(uniform_rand)Mathematica
rand = LibraryFunctionLoad[(*libpath*), "wll_uniform_rand", {{Integer, 1}, Integer}, {Integer, 1}];Generate 10 random integers between 1 and 6:
rand[{1, 6}, 10]C++
#include "wll_interface.h"
wll::matrix<double> transpose(const wll::matrix<double>& mat)
{
wll::matrix<double> mat_t({mat.dimension(1), mat.dimension(0)});
for (size_t i = 0; i < mat.dimension(0); ++i)
for (size_t j = 0; j < mat.dimension(1); ++j)
mat_t(j, i) = mat(i, j);
return mat_t;
}
DEFINE_WLL_FUNCTION(transpose)Mathematica
transpose = LibraryFunctionLoad[(*libpath*), "wll_transpose", {{Real, 2, "Constant"}}, {Real, 2}];C++
#include "wll_interface.h"
wll::sparse_array<double, 2> sparse_identity(size_t size)
{
wll::sparse_array<double, 2> identity({size, size});
for (size_t i = 0; i < size; ++i)
identity(i, i) = 1.0;
return identity;
}
DEFINE_WLL_FUNCTION(sparse_identity)Mathematica
identity = LibraryFunctionLoad[(*libpath*), "wll_sparse_identity", {Integer}, LibraryDataType[SparseArray]];Generate a 10×10 sparse identity matrix:
identity[10]C++
// initialize a tensor with an array of values
wll::matrix<int> tensor3({ }, {{1,0,0}, {0,1,0}, {0,0,1}} );
// initialize a sparse array with a list of position->value rules
wll::sparse_array<int, 2> sparse3({ }, {
wll::pos(0,0) = 1,
wll::pos(1,1) = 1,
wll::pos(2,2) = 1 });