Introduction
A lot of the mathematical implementations we do at NearForm depends on
so-called
mathematical special functions. There is no clearly defined
criteria for what a special function is, but suffice to say they are
functions that often turns up in mathematics and most of them are
notoriously hard to compute. Often they are defined as the solution to
a well-posed problem, however the solution itself is not easy to compute.
JavaScript severely lacks implementations of these special functions,
especially trusted implementations. If you are lucky, you can find
a basic implementation in npm. However, the implementations often have
numerous undocumented issues and only work somewhat well for a
small and undocumented input range.
In R these functions are often built in, and in Python,
SciPy implementations these functions.
Deep within the
SciPy source code, we
find the Cephes library
which is what implements many of these functions.
Cephes is a pure C library, that doesn't depend on anything, including
the
C standard library. This makes it ideal to be compiled to WebAssembly
using emscripten, as it means there won't be calls between JavaScript
and WebAssembly which could otherwise cause performance issues.
We have released the WebAssembly version of Cephes on npm, see
https://www.npmjs.com/package/cephes.
So all you need is to install it with npm install cephes.
Using our Cephes module is very simple, as we have wrapped each WebAssembly
function in a custom JavaScript function that takes care of all the
memory management.
const cephes = require('cephes');
const value = cephes.gamma(2);
Cephes as an Open Source project
Cephes is not the best open source library one could imagine. Firstly,
it lacks a license. However, its author Stephen L. Moshier have kindly
granted us permission to license it as
BSD-3-Clause. Secondly, while the library is maintained it doesn't
use more modern approximation methods for many of the special functions.
The good news is that R and SciPy
are working together on making a better open source library of these
special functions. But it will take a while before that library is
ready, until then Cephes is by far the best choice.