Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>How accurate and how fast does this need to be? You can do something pretty good with a piecewise Chebyshev approximation. You control the accuracy using the order of the Chebyshev approximation (higher order = slower but more accurate). I would also suggest doing argument reduction by decomposing your double into its mantissa (between 1 and 2) and its exponent (a power of two whose logarithm is simply the exponent times <code>log(2)</code>, which you can precompute.)</p> <p>I don't think you can come up with anything very accurate on [0.1, 2] without either doing more arithmetic whenever you want a log or using a huge table and incurring all the caching and unpredictable memory access issues that entails. But do consider doing a piecewise Chebyshev approximation if you have enough time. (If you want me to show you code that uses a Chebyshev approximation, let me know with a comment and I'll update this post.)</p> <p><strong>EDIT</strong>: Code for logarithm using Chebyshev approximation. Accurate within 1e-5.</p> <pre><code>double mylog(double x) { static double logtwo = log(2); static double tbls[4][5] = {{0,0,0,0,0}, {-.9525934480e-2,-.87402539075,-1.135790603,1.1519051721,-1.7063112037}, {.53892330786e-3,-1.0117355213,-.4085197450,-.6242237228,0}, {.60393290013e-6,-1.0001523639,-.4940510719,-.4058961978,0}}; if (x&gt;1) return -mylog(1/x); int expo,e2; x = 1-frexp(x, &amp;expo); double y = frexp(x, &amp;e2); if (e2 &lt; -3) e2 = -3; double *tbl = tbls[-e2]; return expo*logtwo + tbl[0]+x*(tbl[1]+x*(tbl[2]+x*(tbl[3]+x*tbl[4]))); } </code></pre> <p>I calculated the Chebyshev approximations using Maple and expanded them as traditional polynomials for speed.</p> <p>If you want good accuracy very close to 1, you can change <code>if (e2 &lt; -3) e2 = -3</code> and add the row <code>{0,-1,-.5,-1/3.,-.25}</code> to the end of <code>tbls</code> corresponding to Taylor's approximation. If you want it faster, compute a better cubic approximation to log(x) between 1/2 and 3/4 and store it in the first row of <code>tbls</code>.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload