Simon - 9 months ago 66

Python Question

I'm not sure if it's my maths or my Python which isn't up to scratch... but the code below is giving unexpected results. It still plots a circle of points, but in a strange order and a non-uniform manner (even allowing for int rounding errors) i.e. the points aren't sequential around the circle as degree increases, they jump to entirely different points on the circle?

`def pol2cart(distance, angle):`

x = distance * numpy.cos(angle)

y = distance * numpy.sin(angle)

return(x, y)

for fixedangle in xrange(0,360,10):

x, y = pol2cart(50,fixedangle)

print str(int(x)) + ", " + str(int(y)) + " " + str(fixedangle) + "\xb0"

A sample of the result:

`50, 0 0°`

-41, -27 10°

20, 45 20°

7, -49 30°

-33, 37 40°

48, -13 50°

-47, -15 60°

31, 38 70°

-5, -49 80°

-22, 44 90°

43, -25 100°

-49, -2 110°

40, 29 120°

-18, -46 130°

-9, 49 140°

34, -35 150°

-48, 10 160°

46, 17 170°

-29, -40 180°

If 0 degrees = (50,0) then I would expect 10 degrees to be around (49,9) not (-41,-27). And i'd expect 20 degrees to be ~(47,18) not (20,45)... etc. Just with those three examples you can see the Cartesian point has jumped to a completely different quadrant then back again. Even if my ideas about rotation direction, or starting point are completely wrong, I still expect each point to be rotationally sequential either clockwise or anti-clockwise from the 0 degree start point. Plus you can tell from the "square" angles 90 and 180 that the Cartesian point is far from perfectly horizontal or vertical in relation to a (0,0) central point?

Answer

Your code is fine, only problem is that the numpy.cos(angle) takes its argument in radians, not degrees. You can either change the tester to range from 0 to `2*numpy.pi`

or convert the degrees to radians by adding `angle = 180*angle/numpy.pi`

on line 2.