[Tutor] Loop over floating point values

Amit Saha amitsaha.in at gmail.com
Mon Dec 2 07:33:45 CET 2013


On Sun, Dec 1, 2013 at 7:47 PM, spir <denis.spir at gmail.com> wrote:
> 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!).

Depends on what your practice is. This will come up in any problem
where you need a continuous stream of numbers. Like, drawing a circle
with x=rcos(theta) and y=rsin(theta) with theta between 0 to 360.

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)

Yes, IIUC, I think this is an "easier" problem considering that you
care abut the number of passes here more than  you care about the
upper bound of the numbers.

Thanks for sharing.

Best,
Amit.

-- 
http://echorand.me


More information about the Tutor mailing list