numpy.sin function in degrees?

Question:

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.

Asked By: Daniil Ukhorskiy

||

Answers:

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.)

Answered By: BrenBarn

Use the math module from the standard Python library:

>>> math.sin(math.radians(90))
Answered By: Malik Brahimi

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
Answered By: Freeman

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("%fn", 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.

Answered By: Ryan Maguire

Multiplying by pi/180 perform the conversion from degrees to radians. So, np.sin(90*np.pi/180) works as well.

Answered By: romain gal
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.