Where can I inspect Python's math functions?

Tom Scrace picture Tom Scrace · Mar 29, 2011 · Viewed 14.3k times · Source

I would like to look at the way Python does computes square roots, so I tried to find the definition for math.sqrt(), but I can't find it anywhere. I have looked in _math.c, mathmodule.c, and elsewhere.

I know that python uses C's math functions, but are these somewhere in the Python distribution, or are they linked to code elsewhere? I am using Mac OS X.

Where is the algorithm in math.sqrt()?

Answer

Alexei Sholik picture Alexei Sholik · Mar 29, 2011

It depends on the implementation. CPython is using math functions from the standard C library. Jython is most likely using Java's math methods. And so on.

In fact, Python has nothing to do with the actual implementation of math functions. Those are more related to IEEE 754 which is used almost exclusively to represent floating point numbers in computers nowadays.

Anyway, speaking in terms of CPython, its math module is just a thin wrapper over C functions (prooflink, at the bottom of the page). The C functions are implemented as part of the standard C library. It is usually included in OS distributions and it is most likely distributed in binary form, without sources. Note also that many microprocessors have specialised instructions for some of these operations, and your compiler may well make use of those rather than jumping to the implementation in the C library.

I can't tell you the exact algorithm which is used in the standard C library on your system. Some of the possible algorithms are explained here.

In the specific case of OS X, the math functions live in libSystem.dylib, which unfortunately is not Open Source (there is only stub code available on Apple's Open Source site). You can however disassemble it if you are interested - on current systems, try e.g.

otool -tvV /usr/lib/system/libsystem_m.dylib