r/C_Programming • u/New_Telephone926 • Aug 18 '26
Question How are functions in libm actually implemented ?
I'm trying to gather information for a school project about how elementary functions (exp, log, cos, sin, etc.) are implemented on computers, for maximum accuracy and efficiency.
I've already found some information about techniques that can be used to implement these functions, such as range reduction, Taylor series, polynomial approximations or minimax approximations. However, most of what I've found remains fairly theoretical, and I have no idea of what is actually used in the real world.
I tried to reverse-engineer the exp implementation in libm, but my knowledge of C and its intricacies is still fairly limited (though I'm working on improving it).
I'm particularly interested in understanding which approximation methods are actually used, how polynomial coefficients are chosen (Taylor, minimax/Remez, or other), and how implementations balance speed and accuracy.
But really, if you have any information whatsoever, it would be great.
If anyone has documentation, papers, or personal experience with this kind of subject, it would be really helpful.
Thanks in advance!
Edit : Thanks a lot to everyone ! You gave me exactly what I was looking for
35
u/flyingron Aug 18 '26
There's a whole branch of computer science called Numerical Methods on this. The classic text for the basic algorithms is "Numerical Recipes." This has been written to target a couple of languages including C. Authors are:Saul Teukolsky, William H. Press, and William T. Vetterling
5
u/def-pri-pub Aug 18 '26
I wrote about this a little on my blog when I was trying to find a faster approximation for
asin(). It may be tangentially related to your question:3
u/Axman6 Aug 18 '26 edited Aug 18 '26
There’s quite lot of literature on the topic, much of it from the early days of computing. A fairly recent paper that came to mine is https://arxiv.org/pdf/2311.01515.pdf
Elementary Functions by Kenneth Iverson is probably one of the most referenced texts https://link.springer.com/book/10.1007/978-1-4899-7983-4
It can be found online… no idea where I found it though.
2
u/GourmetMuffin Aug 18 '26
The functions you mention use float and do understand how to implement them you need some basics in IEEE754 first:
floats have three bit fields: a sign bit, an exponent and a fraction. The number they describe is (-1)sign * 2exp-2^7+1 * (1 + frac / 223) for single precision, double works the same way but with different numeric constants. If we ignore the sign bit for a moment and say that the exponent is 8 bits and the fraction 23 bits it becomes more obvious that this is a bounded scientific notation in base 2.
Scientific notation can be easily transformed into a pure exponential representation by approximating the exponent corresponding to the fractional term. If you don't care about accuracy you can just translate it linearly from the [0..223) range to [0..1) but using a 3rd or 4th order polynomial yields much better results.
Once you have the 2x representation of e.g. a in powf(a, b) then calculating that becomes a matter of translating 2y, where y = x*b, back to its scientific notation. Using the exponential representation makes a lot of the libm functionality trivial to implement.
2
u/zellforte Aug 19 '26
Here are a couple implementations that are focused on speed and simplicity.
The cosine implementation is literally just one line of code evaluating a simple polynomial, then a couple lines of range reduction and quadrant checks.
https://www.ganssle.com/approx.htm
2
u/Key_Ant_8481 Aug 20 '26
For modern treatment of the libm functions, you can take a look and
Handbook of Floating Point Arithmeticby Jean-Michel Muller, and the CORE-MATH project (https://core-math.gitlabpages.inria.fr/) and other projects listed on their page.13
u/305bootyclapper Aug 18 '26
Are we not allowed to post GitHub links or something? It’s great to look at open source implementations. Eg on most Linux’s the implementation is GNU, which you can see here: https://github.com/kraj/glibc/tree/master/math
GNU tends to be hard to read since their implementations tend to be very general and complicated. Other ones worth looking through would be musl: https://github.com/kraj/musl
And also OpenBSD.
5
u/mikeblas Aug 18 '26
Some implementations use CORDIC: https://www.allaboutcircuits.com/technical-articles/an-introduction-to-the-cordic-algorithm/
8
u/Straight_Mistake_364 Aug 18 '26
Some of the functions you mention, nowadays are implemented directly as floating-point hardware in the CPU/FPU, so the libm functions just invoke the corresponding assembly language instructions.
4
u/P-p-H-d Aug 18 '26
You could read this book and in particular its chapter §4 Elementary and special function evaluation
https://members.loria.fr/PZimmermann/mca/mca-cup-0.5.9.pdf
1
u/sciencekm Aug 18 '26
I suggest that you checkout the book "Software Manual For The Elementary Functions" by Cody and Waite.
2
u/TheChief275 Aug 18 '26
I suspect a lot of them are done through a fast approximation + Newton's method, but don't quote me on that one. Obviously each implementation will also make use of compiler builtins to speed up parts of the algorithms
2
u/DawnOnTheEdge Aug 18 '26 edited Aug 18 '26
Modern math libraries usually calculate polynomial approximations for math functions and compose or interpolate them. Using Horner’s method, these compile to extremely fast series of multiply-add instructions. Other methods might be used in some situations. For example, a Padé approximant, which uses the ratio of two polynomials, can represent trigonometric functions with singularities.
The latest wrinkle is automatically vectorizing loops that call math functions to use SIMD instructions. Intel’s ICX/ICPX compiler has been doing this for years and Microsoft’s allows you to call Intel’s SVML library explicitly. (C++26 is adding support to its standard library by overloading all the math functions for its
std::simdtypes.)2
u/flatfinger Aug 18 '26
Computers have varying levels of hardware support for trig functions, in some cases offering a better combination of accuracy and performance than could be achieved through software alone. Except when hardware support outperforms software, there will seldom be a single best approach for every application. If e.g. one has a number x and wants to compute sin(2πx), code that is designed to compute that function may be faster and more accurate than code which, after normalizing x into the first octant, has to multiply it by 2π, compute a sine or cosine, and then adjust the result to compensate for the normalization (e.g. if x is 0.5001, achieving maximum precision would require computing the sine of 0.0002π and inverting it, rather than computing 1.0002π and taking the sine).