1bbbf1280Sopenharmony_ci// polynomial for approximating log2(1+x)
2bbbf1280Sopenharmony_ci//
3bbbf1280Sopenharmony_ci// Copyright (c) 2019, Arm Limited.
4bbbf1280Sopenharmony_ci// SPDX-License-Identifier: MIT
5bbbf1280Sopenharmony_ci
6bbbf1280Sopenharmony_cideg = 11; // poly degree
7bbbf1280Sopenharmony_ci// |log2(1+x)| > 0x1p-4 outside the interval
8bbbf1280Sopenharmony_cia = -0x1.5b51p-5;
9bbbf1280Sopenharmony_cib =  0x1.6ab2p-5;
10bbbf1280Sopenharmony_ci
11bbbf1280Sopenharmony_ciln2 = evaluate(log(2),0);
12bbbf1280Sopenharmony_ciinvln2hi = double(1/ln2 + 0x1p21) - 0x1p21; // round away last 21 bits
13bbbf1280Sopenharmony_ciinvln2lo = double(1/ln2 - invln2hi);
14bbbf1280Sopenharmony_ci
15bbbf1280Sopenharmony_ci// find log2(1+x)/x polynomial with minimal relative error
16bbbf1280Sopenharmony_ci// (minimal relative error polynomial for log2(1+x) is the same * x)
17bbbf1280Sopenharmony_cideg = deg-1; // because of /x
18bbbf1280Sopenharmony_ci
19bbbf1280Sopenharmony_ci// f = log(1+x)/x; using taylor series
20bbbf1280Sopenharmony_cif = 0;
21bbbf1280Sopenharmony_cifor i from 0 to 60 do { f = f + (-x)^i/(i+1); };
22bbbf1280Sopenharmony_cif = f/ln2;
23bbbf1280Sopenharmony_ci
24bbbf1280Sopenharmony_ci// return p that minimizes |f(x) - poly(x) - x^d*p(x)|/|f(x)|
25bbbf1280Sopenharmony_ciapprox = proc(poly,d) {
26bbbf1280Sopenharmony_ci  return remez(1 - poly(x)/f(x), deg-d, [a;b], x^d/f(x), 1e-10);
27bbbf1280Sopenharmony_ci};
28bbbf1280Sopenharmony_ci
29bbbf1280Sopenharmony_ci// first coeff is fixed, iteratively find optimal double prec coeffs
30bbbf1280Sopenharmony_cipoly = invln2hi + invln2lo;
31bbbf1280Sopenharmony_cifor i from 1 to deg do {
32bbbf1280Sopenharmony_ci  p = roundcoefficients(approx(poly,i), [|D ...|]);
33bbbf1280Sopenharmony_ci  poly = poly + x^i*coeff(p,0);
34bbbf1280Sopenharmony_ci};
35bbbf1280Sopenharmony_ci
36bbbf1280Sopenharmony_cidisplay = hexadecimal;
37bbbf1280Sopenharmony_ciprint("invln2hi:", invln2hi);
38bbbf1280Sopenharmony_ciprint("invln2lo:", invln2lo);
39bbbf1280Sopenharmony_ciprint("rel error:", accurateinfnorm(1-poly(x)/f(x), [a;b], 30));
40bbbf1280Sopenharmony_ciprint("in [",a,b,"]");
41bbbf1280Sopenharmony_ciprint("coeffs:");
42bbbf1280Sopenharmony_cifor i from 0 to deg do coeff(poly,i);
43