SciPy 1.15 is slated to support basic mathematical operations on random variables. For instance, if X
is an object representing a normal random variable, it will support operations like 3*abs(X)**2 + 1
; the resulting random variable follows a shifted scaled chi-squared distribution with one degree of freedom. However, if I understand correctly, there is currently no way to override the behavior of math.exp
or math.log
. To that end, I’d propose that math.exp
and math.log
attempt to delegate to __exp__
and __log__
methods of the argument.
Surprisingly, I haven’t found much discussion on this topic.
math.log and math.log10 domain error on very large Fractions · Issue #87052 · python/cpython · GitHub suggests:
I guess another approach might be to change the math module so that all its functions support franctions (and decimal, and other esoteric number types). But that would require having log and many others as methods on the numeric types.
and later
There’s the rub. We could create a dunder method for every math function and require that every numeric type to support every dunder method.
I don’t mean to propose going that far. math.floor
, math.ceil
, and math.trunc
already delegate to __floor__
, __ceil__
, and __trunc__
. Allowing math.exp
and math.log
to delegate, too, might open the floodgates a little further for similar requests (e.g. math.pow
to behave like pow
), but the precedent is already there.
The exponential and logarithm functions are defined for many mathematical objects, including matrices and quaternions, so there are several other potential use cases besides random variables.
If I understand correctly, there may be hesitation to add the overhead of delegation. However, built-in pow
(which does delegate to __pow__
) seems just as fast as math.pow
for floats, so perhaps this can be done efficiently.
Thanks for considering the suggestion!
Matt
P.S. Mailman 3 Double "at" operator for matmul exponentiation - Python-ideas - python.org mentions that there could be a double “at” operator @@
with associated method __exp__
, but this discussion does not appear to be active any more.