[Python-ideas] Including elementary mathematical functions in the python data model
Mark Dickinson
dickinsm at gmail.com
Sun Sep 26 13:05:11 CEST 2010
On Tue, Sep 21, 2010 at 7:44 PM, Michael Gilbert
<michael.s.gilbert at gmail.com> wrote:
> It would be really nice if elementary mathematical operations such as
> sin/cosine (via __sin__ and __cos__) were available as base parts of
> the python data model [0]. This would make it easier to write new math
> classes, and it would eliminate the ugliness of things like self.exp().
>
> This would also eliminate the need for separate math and cmath
> libraries since those could be built into the default float and complex
> types.
Hmm. Are you proposing adding 'sin', 'cos', etc. as new builtins? If
so, I think this is a nonstarter: the number of Python builtins is
deliberately kept quite small, and adding all these functions (we
could argue about which ones, but it seems to me that you're talking
about around 18 new builtins---e.g., 6 trig and inverse trig, 6
hyperbolic and inverse hyperbolic, exp, expm1, log, log10, log1p,
sqrt) would enlarge it considerably. For many users, those functions
would just be additional bloat in builtins, and there's possibility of
confusion with existing variables with the same name ('log' seems like
a particular candidate for this; 'sin' less likely, but who knows ;-).
A less invasive proposal would be just to introduce __sin__, etc.
magic methods and have math.sin delegate to <type>.__sin__; i.e.,
have math.sin work in exactly the same way that math.floor and
math.ceil currently work. That would be quite nice for e.g., the
decimal module: you'd be able to write something like:
from math import sqrt
root = (-b + sqrt(b*b - 4*a*c)) / (2*a)
to compute the root of a quadratic equation, and it would work
regardless of whether a, b, c were Decimal instances or floats.
I'm not sure how I feel about the entailed magic method explosion, though.
Mark
More information about the Python-ideas
mailing list