I want to loop from 0 radians through 6.2 radians in increment of 0.1 radian

something like this in C

for(r=0.0; r<6.4;r=r+0.1)

this is the best I can do in Python:

for i in range(63):
    z = float(i)/10
    print z

Is there a better way?

Recommended Answers

All 5 Replies

That's fine if you have a nice increment like 0.1, otherwise note that a for loop is just a special case of a while loop.

r = 0.0
while r < 6.4:
    print r
    r += 0.1
print
##
##   and if you have an unusual series of numbers, use a list
iterate_list = [0.0, 0.2, 0.3, 0.5, 0.6]
for r in iterate_list:
    print r

thanks, I looked a long time for a floating point equivalent of "range".

e.g. range(0, 6.4, 0.1)

I guess there is nothing like this?

You actually picked a strange example where the floating point representation error makes a difference ...

r = 6.0
while r < 6.4:
    print r
    r += 0.1
"""my result -->
6.0
6.1
6.2
6.3
6.4  <--- oops! (float rep of 6.4 --> 6.3999999999999986)
"""

This works correctly ...

r = 1.0
while r < 1.4:
    print r
    r += 0.1
"""my result -->
1.0
1.1
1.2
1.3  <--- correct (float rep of 1.3 --> 1.3000000000000003
"""

Actually C or C++ code will give you the same problem ...

#include <stdio.h>

int main()
{
  double r;
  
  for(r = 6.0; r < 6.4; r = r + 0.1)
      printf("%0.1f\n", r);
  
  return 0;
}

/* my result -->
6.0
6.1
6.2
6.3
6.4  <--- oops! (float rep of 6.4 --> 6.3999999999999986)
*/
##   and if you have an unusual series of numbers, use a list
iterate_list = [0.0, 0.2, 0.3, 0.5, 0.6]
for r in iterate_list:
    print r

To continue in this direction, you can use a list you construct the same time (called list comprehension)...
This is not very different of your solution, it simply shorten the code.

for y in [float(i)/10 for i in range(63)]:
    print y,
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.