approx.ts 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. /**
  2. * Copyright (c) 2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
  3. *
  4. * @author Alexander Rose <alexander.rose@weirdbyte.de>
  5. *
  6. * adapted from https://gist.github.com/imbcmdth/6338194
  7. * which is ported from https://code.google.com/archive/p/fastapprox/ (BSD licensed)
  8. */
  9. const _a_fasterPow2 = new ArrayBuffer(4);
  10. const _i_fasterPow2 = new Int32Array(_a_fasterPow2);
  11. const _f_fasterPow2 = new Float32Array(_a_fasterPow2);
  12. export function fasterPow2(v: number) {
  13. const clipNumber = (v < -126) ? -126 : v;
  14. _i_fasterPow2[0] = ((1 << 23) * (clipNumber + 126.94269504));
  15. return _f_fasterPow2[0];
  16. }
  17. export function fasterExp(v: number) {
  18. return fasterPow2(1.442695040 * v);
  19. }
  20. const _a_fasterLog2 = new ArrayBuffer(4);
  21. const _i_fasterLog2 = new Int32Array(_a_fasterLog2);
  22. const _f_fasterLog2 = new Float32Array(_a_fasterLog2);
  23. export function fasterLog2(v: number) {
  24. _f_fasterLog2[0] = v;
  25. const t = _i_fasterLog2[0] * 1.1920928955078125e-7;
  26. return t - 126.94269504;
  27. }
  28. export function fasterLog(v: number) {
  29. return 0.6931471805599453 * fasterLog2(v);
  30. }
  31. export function fasterLog10(v: number) {
  32. return 0.30102999566398114 * fasterLog2(v);
  33. }