As a warning, none of these answers will work for very large inputs.
numpy
's deg2rad
function simply multiplies the argument by pi/180.
The source for this is here (at the C level).
Imprecision in this value will result in horrible error. For example:
import numpy
def cosd(x):
return numpy.cos(numpy.deg2rad(x))
print(cosd(1.0E50)) # Prints -0.9999338286702031
Let's try this in C with some standard library tricks.
#include <stdio.h>
#include <math.h>
#define cosd(x) cos(fmod((x), 360.0) * M_PI / 180.0)
int main(void)
{
const double x = 1.0E50;
printf("%f\n", cosd(x));
return 0;
}
This prints out 0.766044
, so our cosd
function in Python is off by about 2, when the function is bounded between -1 and 1!
It seems numpy
has a mod function. Let's duplicate this C routine using that.
import numpy
def cosd(x):
return numpy.cos(numpy.deg2rad(numpy.mod(x, 360.0)))
print(cosd(1.0E50)) # 0.7660444431189778
And all is well.