xref: /freebsd/contrib/arm-optimized-routines/math/tools/log2.sollya (revision 072a4ba82a01476eaee33781ccd241033eefcf0b)
131914882SAlex Richardson// polynomial for approximating log2(1+x)
231914882SAlex Richardson//
331914882SAlex Richardson// Copyright (c) 2019, Arm Limited.
4*072a4ba8SAndrew Turner// SPDX-License-Identifier: MIT OR Apache-2.0 WITH LLVM-exception
531914882SAlex Richardson
631914882SAlex Richardsondeg = 11; // poly degree
731914882SAlex Richardson// |log2(1+x)| > 0x1p-4 outside the interval
831914882SAlex Richardsona = -0x1.5b51p-5;
931914882SAlex Richardsonb =  0x1.6ab2p-5;
1031914882SAlex Richardson
1131914882SAlex Richardsonln2 = evaluate(log(2),0);
1231914882SAlex Richardsoninvln2hi = double(1/ln2 + 0x1p21) - 0x1p21; // round away last 21 bits
1331914882SAlex Richardsoninvln2lo = double(1/ln2 - invln2hi);
1431914882SAlex Richardson
1531914882SAlex Richardson// find log2(1+x)/x polynomial with minimal relative error
1631914882SAlex Richardson// (minimal relative error polynomial for log2(1+x) is the same * x)
1731914882SAlex Richardsondeg = deg-1; // because of /x
1831914882SAlex Richardson
1931914882SAlex Richardson// f = log(1+x)/x; using taylor series
2031914882SAlex Richardsonf = 0;
2131914882SAlex Richardsonfor i from 0 to 60 do { f = f + (-x)^i/(i+1); };
2231914882SAlex Richardsonf = f/ln2;
2331914882SAlex Richardson
2431914882SAlex Richardson// return p that minimizes |f(x) - poly(x) - x^d*p(x)|/|f(x)|
2531914882SAlex Richardsonapprox = proc(poly,d) {
2631914882SAlex Richardson  return remez(1 - poly(x)/f(x), deg-d, [a;b], x^d/f(x), 1e-10);
2731914882SAlex Richardson};
2831914882SAlex Richardson
2931914882SAlex Richardson// first coeff is fixed, iteratively find optimal double prec coeffs
3031914882SAlex Richardsonpoly = invln2hi + invln2lo;
3131914882SAlex Richardsonfor i from 1 to deg do {
3231914882SAlex Richardson  p = roundcoefficients(approx(poly,i), [|D ...|]);
3331914882SAlex Richardson  poly = poly + x^i*coeff(p,0);
3431914882SAlex Richardson};
3531914882SAlex Richardson
3631914882SAlex Richardsondisplay = hexadecimal;
3731914882SAlex Richardsonprint("invln2hi:", invln2hi);
3831914882SAlex Richardsonprint("invln2lo:", invln2lo);
3931914882SAlex Richardsonprint("rel error:", accurateinfnorm(1-poly(x)/f(x), [a;b], 30));
4031914882SAlex Richardsonprint("in [",a,b,"]");
4131914882SAlex Richardsonprint("coeffs:");
4231914882SAlex Richardsonfor i from 0 to deg do coeff(poly,i);
43