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