Reputation: 1
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?
Upvotes: 0
Views: 2589
Reputation: 231375
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
Upvotes: 3