1

I'm working on a Python exercise in which I will rotate a 2d vector counterclockwise by theta degree. Here is the function I wrote

import math
def rotate(coordinate,theta):
    theta=math.radians(theta)
    x=coordinate[0]
    y=coordinate[1]
    coordinate[0]=x*math.cos(theta)-y*math.sin(theta)
    coordinate[1]=x*math.sin(theta)+y*math.cos(theta)

    return coordinate

where coordinate is a list that contains the x and y value of the vector.

However, when I try to call this function in the following way, something weird happened.

 points=[]   
 test=[1,0]   # a test vector

 #rotate the test vector 360 times
 for j in range(360):
   #print(rotate(test,j))
   points.append(rotate(test,j))

 #print the content of the vectors after rotation
 for item in points:
     print(item)

In the code above, I have a test vector [1,0] and I would like to rotate it 360 times, and the rotated vector will be add to the list "points". However, if I print the content of list "points", I got

[1.0000000000000002, -4.098804629038e-14]
[1.0000000000000002, -4.098804629038e-14]
[1.0000000000000002, -4.098804629038e-14]
[1.0000000000000002, -4.098804629038e-14]
[1.0000000000000002, -4.098804629038e-14]
[1.0000000000000002, -4.098804629038e-14]
[1.0000000000000002, -4.098804629038e-14]
[1.0000000000000002, -4.098804629038e-14]
 ...

which suggests the vector has not been rotated at all!

I know this error can be fixed in many ways, but I still don't quite understand why this happens. Could anyone give some explanations? Thank you.

user2226358
  • 195
  • 1
  • 2
  • 13
  • `rotate` takes a list and modifies it *in-place*. your loop is rotating the same list (`test`) over and over again, each time putting a new 'reference' to it in `points`. In the end, `points` contains 360 references to the `test` list. – Tom Dalton Jun 06 '18 at 15:56
  • https://stackoverflow.com/q/240178/5496433 – BallpointBen Jun 06 '18 at 15:57
  • You need to copy your list - you got a list of ints, ints are immuteables so a `points.append(rotate(test,j)[:])` does the trick - you get lots of different values as results – Patrick Artner Jun 06 '18 at 15:57

0 Answers0