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()
?
We use the getsource() method of inspect module to get the source code of the function. Returns the text of the source code for an object. The argument may be a module, class, method, function, traceback, frame, or code object. The source code is returned as a single string.
Introduction. The Python Math Library provides us access to some common math functions and constants in Python, which we can use throughout our code for more complex mathematical computations. The library is a built-in Python module, therefore you don't have to do any installation to use it.
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
Some modules are written in C and not in python so you wouldn't be able to find the .py files. For a list of these you can use:
import sys
print sys.builtin_module_names
Since it's written in C you will have to find it in the source code. If you have the source already it's in the modules directory.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With