1// polynomial for approximating log2(1+x) 2// 3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4// See https://llvm.org/LICENSE.txt for license information. 5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 7deg = 11; // poly degree 8// |log2(1+x)| > 0x1p-4 outside the interval 9a = -0x1.5b51p-5; 10b = 0x1.6ab2p-5; 11 12ln2 = evaluate(log(2),0); 13invln2hi = double(1/ln2 + 0x1p21) - 0x1p21; // round away last 21 bits 14invln2lo = double(1/ln2 - invln2hi); 15 16// find log2(1+x)/x polynomial with minimal relative error 17// (minimal relative error polynomial for log2(1+x) is the same * x) 18deg = deg-1; // because of /x 19 20// f = log(1+x)/x; using taylor series 21f = 0; 22for i from 0 to 60 do { f = f + (-x)^i/(i+1); }; 23f = f/ln2; 24 25// return p that minimizes |f(x) - poly(x) - x^d*p(x)|/|f(x)| 26approx = proc(poly,d) { 27 return remez(1 - poly(x)/f(x), deg-d, [a;b], x^d/f(x), 1e-10); 28}; 29 30// first coeff is fixed, iteratively find optimal double prec coeffs 31poly = invln2hi + invln2lo; 32for i from 1 to deg do { 33 p = roundcoefficients(approx(poly,i), [|D ...|]); 34 poly = poly + x^i*coeff(p,0); 35}; 36 37display = hexadecimal; 38print("invln2hi:", invln2hi); 39print("invln2lo:", invln2lo); 40print("rel error:", accurateinfnorm(1-poly(x)/f(x), [a;b], 30)); 41print("in [",a,b,"]"); 42print("coeffs:"); 43for i from 0 to deg do coeff(poly,i); 44