Search code examples
pythonarraysradians

convering degrees to radians inside an array


I have an array A,

array([[ 1,  2, 25],
       [ 3,  4, 23],
       [ 2,  6, 55],
       [ 9,  7, 78],
       [11,  5, 47]])

I changed the last column of the array, supposedly degree values (25,23,55,78,47) to radians.

its quite easy to do it, I did:

A_rad[:,2] = np.pi/180 *A[:,2]

you can also use np.radians, the output is:

    array([[ 1,  1,  0],
           [ 2,  3,  0],
           [ 3,  2,  0],
           [ 9,  5,  0],
           [11,  3,  0]])

surely the last columns need to be changed, but not to zeros, i changed also the data type from int to float, the output were only 0., I need at least 3 decimals places in order to solve my problems.

The last column should give output as array([0.4363, 0.4014, 0.9599, 1.3614, 0.8203]). The thing is python doesn't save the decimals in the memory, so even if i multiply it always gives 0.

Is python able to do it?

any ideas.


Solution

  • You should cast your array to float:

    import numpy as np
    
    A = np.array([
        [ 1,  2, 25],
        [ 3,  4, 23],
        [ 2,  6, 55],
        [ 9,  7, 78],
        [11,  5, 47]
    ]).astype(float)
    
    A[:,2] = np.radians(A[:,2])
    
    print(A)
    

    This produces:

    [[ 1.          2.          0.43633231]
     [ 3.          4.          0.40142573]
     [ 2.          6.          0.95993109]
     [ 9.          7.          1.36135682]
     [11.          5.          0.82030475]]
    

    BTW: Instead of casting, you could also define the data type during initialization like so: A = np.array([...], dtype=float)