On 12/01/2013 10:03 AM, Amit Saha wrote:
Hello,
Much to my disbelief, I realized I hadn't written a program in Python
as far as I can recall which required me to do something like this, in
psuedocode:
x = 0.1
for i = 0 to x step 0.01
# do something with i
end i
Simply stated, I want to start from say a value, 0 and go upto 0.1 in
increments of 0.01. I don't want to create a list with the values
hard-coded and then iterate over it, and hence I would use a while
loop instead:
x = 0.1
while i < x:
# do something with i
i += 0.01
I think this is one case, where you definitely cannot do this with a
for loop assuming the following restrictions:
- Do not create a list of the floating point values as i=[0.01, 0.02,
0.03..] - either like that or by using a suitable mathematical formula
combined with a list comprehension
- Use numpy's linspace() to create the list for you
Thoughts?
There is a general solution for this (a typical school problem ;-), maybe the
reason why we rarely meet it in practice!). However, watch the issues with
binary floats mentionned by Steven.
# loop from x0 to x1 with step dx, total n passes
x0, x1, dx, n = -0.3, 0.8, 0.2, 6
for i in range(n):
x = x0 + dx * i
print(x)
_______________________________________________
Tutor maillist - Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor