0

I am converting a MATLAB program to Python for a project. I am facing some major issues with converting MATLAB's sind() syntax to Python. I'm using

numpy.sin(numpy.radians())

but some of the results in Python compared to Matlab are displaying tremendous variations. Is there an easier way to tell Python in degrees instead of radians?

5
  • What you need is numpy.deg2rad, or just deg_array/180*np.pi. As far as I know numpy.sin will only accept radians as input. Commented Mar 29, 2017 at 17:30
  • 2
    You have a bug somewhere. We can't tell what it is. Converting degrees to radians with numpy.radians and computing the sine with numpy.sin should not cause catastrophic error relative to a function that takes degrees directly. Commented Mar 29, 2017 at 17:37
  • Nevermind, I had no idea that there was an equivalent numpy.radians, sorry. Commented Mar 29, 2017 at 17:37
  • 3
    Can you show examples of problematic input and corresponding output? Commented Mar 29, 2017 at 17:41
  • why are you using numpy.sin? I normally use from math import sin, pi and then something like sin(30*pi/180.) will give me what I want. Commented Mar 29, 2017 at 17:52

1 Answer 1

3

In Octave, sind is:

function y = sind (x)
  ...
  I = x / 180;
  y = sin (I .* pi);
  y(I == fix (I) & isfinite (I)) = 0;
endfunction

np.radians (np.deg2rad) is, according to a note x * pi / 180.

So for most values np.sin(np.radians(x)) should be the same as sind(x). There might be some variation off at the limits of floating point precision. Also I'm not sure what that last line is supposed to be doing.

In [327]: np.sin(np.radians(0))
Out[327]: 0.0
In [328]: np.sin(np.radians(90))
Out[328]: 1.0
In [329]: np.sin(np.radians(180))
Out[329]: 1.2246467991473532e-16

>> sind(0)
ans = 0
>> sind(90)
ans =  1
>> sind(180)
ans = 0

The Octave docs add: Returns zero for elements where 'X/180' is an integer.

So yes there may be differences, but 1e-16 is not a tremendous difference.

I can replicate sind with:

def sind(x):
    I = x/180.
    y = np.sin(I * np.pi)
    mask = (I == np.trunc(I)) & np.isfinite(I)
    y[mask] = 0
    return y

In [356]: x=np.array([0,90,180,359,360])
In [357]: np.sin(np.radians(x))
Out[357]: 
array([  0.00000000e+00,   1.00000000e+00,   1.22464680e-16,
        -1.74524064e-02,  -2.44929360e-16])
In [358]: sind(x)
Out[358]: array([ 0.        ,  1.        ,  0.        , -0.01745241,  0.        ])

>> x=[0,90,180,359, 360]
x =
     0    90   180   359   360
>> sind(x)
ans =
   0.00000   1.00000   0.00000  -0.01745   0.00000

Not the answer you're looking for? Browse other questions tagged or ask your own question.