loop help

  • Thread starter Gorlon the Impossible
  • Start date
G

Gorlon the Impossible

Hello. I am using Python 2.3.5 with IDLE 1.0.5 on a Windows98 PC.
I have some programming experience but mostly I am still learning.
I am having some trouble understanding the behaviour of a piece of
code I have written. It plots points using PIL.
Here is my loop:

triangle = [(320,27),(172,323),(468,323)]
currentpoint = (randint(0,640),randint(0,350))
t = 0
while t < 10:
ct = choice(triangle)
mp = (currentpoint[0] + ct[0])/2, (currentpoint[1] + ct[1])/2
draw.point(mp,(0,0,0))
currentpoint = mp
t = t + 1

This works fine. But, if I try to divide by a floating point number in
the calculation of mp, instead of mp being overwritten each time thru
the loop, it starts accumulating, leading to overflow errors for large
values of t.
Why is this?
 
B

Ben Sizer

What do you mean by 'it starts accumulating' in this context? Are you
talking about the fact that numbers gain decimal places? Or the fact
that using a number between 0 and 1 will make your values diverge to
infinity? Either way, it's just mathematics for you, I'm afraid, and
there's little Python can do about it. ;)

Which part of the code issues the overflow error? I'm guessing it's the
draw.point() call since that's the only bit I can't test.
 
S

Steven D'Aprano

Hello. I am using Python 2.3.5 with IDLE 1.0.5 on a Windows98 PC.
I have some programming experience but mostly I am still learning.
I am having some trouble understanding the behaviour of a piece of
code I have written. It plots points using PIL.
Here is my loop:

triangle = [(320,27),(172,323),(468,323)]
currentpoint = (randint(0,640),randint(0,350))
t = 0
while t < 10:

Let me guess... you're a C programmer, right?

This is bad practice. The preferred idiom is to do something like
this:

for t in range(10):
# loop

Why manage your own loop variable, inefficiently duplicating code that
already exists in Python?
ct = choice(triangle)
mp = (currentpoint[0] + ct[0])/2, (currentpoint[1] + ct[1])/2
draw.point(mp,(0,0,0))
currentpoint = mp
t = t + 1

This works fine. But, if I try to divide by a floating point number in
the calculation of mp, instead of mp being overwritten each time thru
the loop, it starts accumulating, leading to overflow errors for large
values of t.
Why is this?

Please explain your problem first. In particular, show us the code that
you use that "it (what?) starts accumulating".
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,271
Messages
2,571,357
Members
48,042
Latest member
DoraMcBrie

Latest Threads

Top