I want to known how to implement the math.exp()
function in python. Where in the Python source code is math.exp()
defined?
This one is a little tricky.
The math
module is implemented in a C module, mathmodule.c
. At the end of that file there is a specific Python library structure that defines exp
as implemented by math_exp
:
static PyMethodDef math_methods[] = {
# ...
{"exp", math_exp, METH_O, math_exp_doc},
but math_exp
itself is actually defined via the FUNC1
macro, using the math_1
wrapper function to call the C library exp
function with some error handling and type conversion:
FUNC1(exp, exp, 1,
"exp(x)\n\nReturn e raised to the power of x.")
However, the C function implementation itself is entirely platform dependent, and on modern hardware is usually taken care of in hardware. You would have to turn to a software version of the function to find a starting point to implement this in Python.
You could use the fdlibm
implementation as such a starting point, perhaps, here is a link to the exp
function implementation in C from that library:
or you could refer to this implementation instead:
exp
in hardware as a single instruction. Some legacy 32-bit x86 math libraries might have used x87 instructions for it, but even that's just microcoded, not truly dedicated hardware. Normally you stuff the integer part of the exponent into the exponent field of a float
, and use a polynomial approximation to exp
over the fractional part. –
Harelda © 2022 - 2024 — McMap. All rights reserved.
mathmodule.c
file. – Skerrymath.exp
is defined. At what line number? What file? – Skerryexp
as an application of the Cexp
function wrapped by themathmodule.c
-definedmath_1
function. The implementation of the C function depends on your platform libraries. – Skerry