Reputation: 673
I'm working on a problem that has to do with calculating angles of refraction and what not. However, it seems that I'm unable to use the numpy.sin() function in degrees. I have tried to use numpy.degrees() and numpy.rad2deg().
numpy.sin(90)
numpy.degrees(numpy.sin(90))
Both return ~ 0.894 and ~ 51.2 respectively.
Thanks for your help.
Upvotes: 66
Views: 153757
Reputation: 1014
FIY. SciPy provides the sin function which accepts degrees: https://docs.scipy.org/doc/scipy/reference/generated/scipy.special.sindg.html#scipy.special.sindg
In [2]: import scipy.special as special
In [3]: special.sindg(90)
Out[3]: 1.0
Upvotes: 0
Reputation: 413
Multiplying by pi/180
perform the conversion from degrees to radians. So, np.sin(90*np.pi/180)
works as well.
Upvotes: 0
Reputation: 107
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.
Upvotes: 2
Reputation: 6226
You can define the following symbols to work in degrees:
sind = lambda degrees: np.sin(np.deg2rad(degrees))
cosd = lambda degrees: np.cos(np.deg2rad(degrees))
print(sind(90)) # Output 1.0
Upvotes: 3
Reputation: 16721
Use the math
module from the standard Python library:
>>> math.sin(math.radians(90))
Upvotes: 20
Reputation: 251598
You don't want to convert to degrees, because you already have your number (90) in degrees. You need to convert 90 from degrees to radians, and you need to do it before you take the sine:
>>> np.sin(np.deg2rad(90))
1.0
(You can use either deg2rad
or radians
.)
Upvotes: 96