Reputation: 101
Is it just me or everyone who is facing so many problems in attempting this question from exercise of Think Python. I am trying to solve exercises of Chapter 4 but facing so many problem. Exercise 4.5 says Write a program that draws an Archimedes spiral. I have this code but its not working in Python. I need an easy possible solution for this. Kindly help.
from TurtleWorld import *
world = TurtleWorld()
bob = Turtle()
def polygon(t, length, n):
t = Turtle()
for i in range(n):
fd(t, length)
lt(t, 300 / n)
polygon(bob, 5, 8)
Upvotes: 0
Views: 2176
Reputation: 41872
[In the following discussion, I'm using the turtle library that comes with Python, not TurtleWorld, so adjust accordingly.] From the online ThinkPython PDF:
Exercise 4.5. Read about spirals at http://en.wikipedia.org/wiki/Spiral ; then write a program that draws an Archimedian [sic] spiral (or one of the other kinds). Solution: http://thinkpython.com/code/spiral.py
If we follow the Wikipedia link from Spiral to Archimedean spiral, we end up with with the formula r = a + b * theta
which naturally wants to be computed in polar coordinates and plotted in cartesian coordinates:
def spiral(turtle, rotations=6, a=0.0, b=5):
theta = 0.0
while theta < rotations * 2 * pi:
radius = a + b * theta
x, y = radius * cos(theta), radius * sin(theta)
turtle.goto(x, y)
theta += 0.1
Where a
controls the initial angle of the spiral, and b
controls the distance between turnings:
But the solution that ThinkPython offers is different:
To get rid of pi
, sin()
and cos()
from math.py, it pictures the turtle on the spiral and what each move along that spiral looks like. It introduces n
which is how many line segments to draw, and length
the length of those segments. The b
variable still means roughly the same thing, though on a different scale, and a
represents how tight the initial spiral starts out. Again, we start with:
theta = 0.0
But instead of looping over the number of complete rotations, we loop up to n
, the number of segments to draw. So n
should be large, e.g. 1000 instead of 5 in your code. Each iteration we move forward length
pixels and then calculate a new delta angle to turn based on a
, b
, and theta
:
delta = 1 / (a + b * theta)
We turn by this small amount and also add this amount to theta
just before we loop again. In this approach, a
and b
are typically less than 1 but non-zero:
You can see by the turtle's orientation in the two images that the first is just plotting points so the turtle's orientation isn't significant but in the second we're moving along the spiral so the turtle is always pointing in the direction of the growing spiral. I hope this discussion of the two approaches helps you.
Upvotes: 1