I am working on the task in which I have to make a circle which is having n number of equal parts. I am provided with centre and radius of the circle which is (0,0) and 4 respectively. To achieve this task, I have written below code,
parts = 36 # desire number of parts of the circle
theta_zero = 360/parts
R = 4 # Radius
x_p = []
y_p = []
n = 0
for n in range(0,36):
x_p.append(R * math.cos(n*theta_zero))
y_p.append(R * math.sin(n*theta_zero))
However, after running this code, I got output like below which does not seem a coorect which I am suppose to have.
Kindly let me know what I am doing wrong and give some suggestion of correct code. Thank you
CodePudding user response:
Aside from the fact that you are generating numbers in degrees and passing them to a function that expects radians, there's a much simpler and less error-prone method for generating evenly-spaced coordinates:
t0 = np.linspace(0, 2 * np.pi, parts, endpoint=False)
x0 = R * np.cos(t0)
y0 = R * np.sin(t0)
endpoint=False
ensures that you end up with 36 partitions rather than 35, since otherwise 0
and 2 * np.pi
would overlap.
If you wanted to connect the dots for your circle, you would want the overlap. In that case, you would do
t1 = np.linspace(0, 2 * np.pi, parts 1)
x1 = R * np.cos(t1)
y1 = R * np.sin(t1)
Here is how you would plot a circle with the 36 sectors delineated:
plt.plot(x1, y1)
plt.plot(np.stack((np.zeros(parts), x0), 0),
np.stack((np.zeros(parts), y0), 0))
Finally, if you want your circle to look like a circle, you may want to run plt.axis('equal')
after plotting.
CodePudding user response:
Your circle is weird because math.cos
and math.sin
accept radians while you are passing degrees. You just need to convert the degrees to radians when calling the math functions.
Like this:
parts = 36
theta_zero = 360/parts
R = 4
x_p = []
y_p = []
for n in range(0,36):
x_p.append(R * math.cos(n*theta_zero /180*math.pi))
y_p.append(R * math.sin(n*theta_zero /180*math.pi))
Result:
Alternatively changing theta_zero
to 2*math.pi/parts
would also work and would be slightly faster but it might be a little less intuitive to work with.
Also as @Mad Physicist mentioned you should probably add plt.axis('equal')
to unstretch the image.