Log Library - How is it done in the library code?

Richard A. O'Keefe ok at goanna.cs.rmit.oz.au
Thu Mar 14 10:01:54 AEST 1991


In article <1991Mar12.014416.4289 at m.cs.uiuc.edu>,
joshi at m.cs.uiuc.edu (Anil Joshi) writes:
> I do not want the accuracy that might have been provided in the C library
> log().  It might be spending more time than necessary to calculate more
> accurately than I want it to be. 

Have you *measured* it?  If you are using a system with a floating-point
coprocessor chip (80*87, 6888[12], 32*81, Weitek, ...) there is a strong
likelihood that the C function log() will map onto a single coprocessor
instruction, and that in turn is likely to be considerably faster than
anything you can cobble together.  Even if your machine has no log()
instruction or other direct support for log(), remember that the people
who work on floating point libraries are usually GOOD at it.

Just now as a check I took a look at the code for one implementation of
log().  Unless your program is spending almost all its time computing
logarithms, there isn't going to be a lot of point in trying to do better.
Basically, the kind of thing that goes on in a function like this is:
    1.  Check that the argument is in range (handle infinity, NaN, 
	subnormals, 0, negative numbers, &c)   
    2.  Argument reduction:  re-express the number as 2**k * (1+f).
    3.	Calculate t = log2(1+f) using some clever method.
    4.  Return (k + t) * log(2)	

If you know that your numbers are in range, you can eliminate 1, but
the people who wrote your library already knew that it was a good idea
to make the "everything in order" path as fast as possible.
If you know a _lot_ about your numbers, you may be able to eliminate
2, but there are C library functions for that step so it probably isn't
_worth_ eliminating.
3 is the tricky bit, but unless you are a numerical analyst or have the
help of one (and from the postings this does not seem to be the case)
it may not be obvious just how far to take your series or table to get
the accuracy you do want.  Perhaps surprisingly, you aren't likely to
save very much.

As a particular point:  extrapolating in a table is very likely to be
SLOWER than your C system's log() function.

I really can't stress enough that for the elementary transcendental
functions, you should only consider writing your own once you have
MEASURED them and found them to be too slow in context or too inaccurate.
And you should by no means use your own log() until you have measured its
accuracy:  it might be much worse than you think!  For this purpose, the
ELEFUNT (ELEmentary FUNction Testing) library is extremely valuable; you
can get it from netlib.

-- 
The purpose of advertising is to destroy the freedom of the market.



More information about the Comp.lang.c mailing list