degrees and radians.

Steven D'Aprano steve+comp.lang.python at pearwood.info
Wed Aug 24 01:26:44 EDT 2016


On Wednesday 24 August 2016 14:26, Gary Herron wrote:

> Do you really need anything more complex than this?
> 
>  >>> toRadians = math.pi/180.0
> 
>  >>> math.sin(90*toRadians)
> 1.0
> 
> Perhaps I'm not understanding what you mean by "clunky",  but this seems
> pretty clean and simple to me.

The math module has two conversion functions, math.radians() and 
math.degrees().


Some other languages (Julia, by memory, and perhaps others) have dedicated 
sind(), cosd(), tand() or possibly dsin(), dcos(), dtan() functions which take 
their argument in degrees and are more accurate than doing a conversion to 
radians first. I'd like to see that.

I've also seen languages with sinp() etc to calculate the sine of x*pi without 
the intermediate calculation.

But if I were designing Python from scratch, I'd make sin(), cos() and tan() 
call dunder methods __sin__ etc:


def sin(obj):
    if hasattr(type(obj), '__sin__'):
        y = type(obj).__sin__()
        if y is not NotImplemented:
            return y
    elif isinstance(obj, numbers.Number):
        return float.__sin__(float(obj))
    raise TypeError

Likewise for asin() etc.

Then you could define your own numeric types, such as a Degrees type, a 
PiRadians type, etc, with their own dedicated trig function implementations, 
without the caller needing to care about which sin* function they call.




-- 
Steve




More information about the Python-list mailing list