-1

I'm a beginner programmer trying to code my own version of python 3.9's math.sqrt(), just for fun and as a little challenge. The math.sqrt() is much faster than anything I've created, so I'm curious how the developers created the function.

Is there a way for me to see the code for the function?

Thanks.

nicola
  • 1
  • 2
    Does this answer your question? [Where can I inspect Python's math functions?](https://stackoverflow.com/questions/5476189/where-can-i-inspect-pythons-math-functions) – enzo May 08 '21 at 01:19

1 Answers1

0

It depends on the implementation, but for (virtually) all Python versions, the basic math functions are simply coded with in-line insertion, in assembler language, of the corresponding on-chip function. Thus, math.sqrt resolves directly to loading your argument and then using the CPU's SQRT function for that data type, and leaving the result in the return register.

Prune
  • 76,765
  • 14
  • 60
  • 81
  • A bit of extra detail - while almost all the `math` functions have a source available in [the cpython repo](https://github.com/python/cpython/blob/bb3e0c240bc60fe08d332ff5955d54197f79751c/Modules/mathmodule.c), sqrt does not. I'm like 70% sure it's just straight-up using the direct C standard libary implementation. – Green Cloak Guy May 08 '21 at 01:26
  • 1
    I've seen the C library code, at least for the compilers we use at work. It's an in-line to the CPU function. I've worked with this for the x86 and 960 architectures. – Prune May 08 '21 at 01:31