ftb-trigo
Need fast approximated trigonometric functions for your javascript projects (vizualisations, games...) ?
ftb-trigo uses neat algorithms designed by Jasper Vijn and Andrew Steadman for that :
- target modern browsers and NodeJs
- fast
- tiny (about 1 kB)
- precision can be changed on-the-fly
How It Works
- based on algorithms originally developped for embedded systems (IoT). Due to low speeds and limited hardware capabilities, they use integers instead of floating-point values, and bit-shifting and various symmetry tricks for evaluating trigonometric functions instead of lookup tables.
- built using the WebAssembly technology, offering nearly native performance and small build sizes.
- minimalistic javascript wrapper to notify the WebAssembly code when one wants to find the right balance between precision and speed.
Howto
Installing
Browser without building process
- Use the following CDN :
https://cdn.jsdelivr.net/npm/ftb-trigo@0.3.4
- In your code :
const { sin, cos, setQuality, getQuality } = await trigo();
Via package managers
-
With
npm
:$ npm install --save ftb-trigo
-
With
yarn
:$ yarn add ftb-trigo
Using
-
Without CDN only :
import ftb-trigo from 'ftb-trigo';
Switching the precision on-the-fly
-
Getting the functions :
const { sin, cos, setQuality, getQuality } = await trigo();
-
Using sin() and cos() as usual (values in radians).
-
Changing the precision / speed as follows, thanks to the arbitrary
quality
setting :setQuality(0) // crappy quality, for very low CPU consumption // or setQuality(50) // default setting: very good approximation (0.01% Full-Scale). // or setQuality(100) // switch to the host trigonometric functions (Math.sin, Math.cos)
Note : only 3 quality steps at the moment, more to come hopefully :
- from 0 to 33 : 4-th order approximation.
- from 34 to 66 : 5-th order approximation.
- from 67 to 100 : using Math.sin, Math.cos, etc.
Choosing a specific approximation
-
Getting a specific approximation :
const { sin_X, cos_X } = await trigo();
Where X is currently restricted to 4 and 5 (ex: sin_4), the currently available approximation orders.