Programming Question

Darrell news at dorb.com
Tue Sep 21 09:56:34 EDT 1999


Fixed point is good, but you can do it with floats also.
I'm expecting the next post to tell us that a floating point range already
exists :)

>>> def fRange(a,b,i=1.0,precision=3):
...     res=[]
...     while a <=b:
...         res.append(a)
...         a=a+i
...         a=round(a,precision)
...     return res
...
>>> fRange(-4.0, 4.0)
[-4.0, -3.0, -2.0, -1.0, 0.0, 1.0, 2.0, 3.0, 4.0]
>>> fRange(-4.0, 4.0, 0.1)
[-4.0, -3.9, -3.8, -3.7, -3.6, -3.5, -3.4, -3.3, -3.2, -3.1, -3.0, -2.9, -2.
8, -
2.7, -2.6, -2.5, -2.4, -2.3, -2.2, -2.1, -2.0, -1.9, -1.8, -1.7, -1.6, -1.5,
 -1.
4, -1.3, -1.2, -1.1, -1.0, -0.9, -0.8, -0.7, -0.6, -0.5, -0.4, -0.3, -0.2, -
0.1,
 0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.3, 1.4,
1.5,
 1.6, 1.7, 1.8, 1.9, 2.0, 2.1, 2.2, 2.3, 2.4, 2.5, 2.6, 2.7, 2.8, 2.9, 3.0,
3.1,
 3.2, 3.3, 3.4, 3.5, 3.6, 3.7, 3.8, 3.9, 4.0]

--
--Darrell
Matthew Hirsch <hirsch at noreaster.cit.cornell.edu> wrote in message
news:37E7809E.A871480C at noreaster.cit.cornell.edu...
> Hi,
>
> I'm still a little confused about precision and roundoff error.  Can
> someone please explain to me why this loop isn't working.  I'm trying to
> get a printout of all 81 numbers between -4.0 and 4.0 in 0.1
> increments.  The problem is that in the final iteration, a's value is
> becoming greater than 4.  It shows up as something like
> 4.0000000000000000000xxxxx.  What can I do to get around this problem?
> I would greatly appreciate anybody's help.
>
> Thanks,
> Matt
>
> Here's the loop:
>
> >>> a=-4.0
> >>> b=4.0
> >>> i=.1
> >>> while a <= b:
> ...     print a
> ...     a=a+i
> ...
> -4.0
> -3.9
> -3.8
> -3.7
> -3.6
> -3.5
> -3.4
> -3.3
> -3.2
> -3.1
> -3.0
> -2.9
> -2.8
> -2.7
> -2.6
> -2.5
> -2.4
> -2.3
> -2.2
> -2.1
> -2.0
> -1.9
> -1.8
> -1.7
> -1.6
> -1.5
> -1.4
> -1.3
> -1.2
> -1.1
> -1.0
> -0.9
> -0.8
> -0.7
> -0.6
> -0.5
> -0.4
> -0.3
> -0.2
> -0.1
> 2.41473507856e-15
> 0.1
> 0.2
> 0.3
> 0.4
> 0.5
> 0.6
> 0.7
> 0.8
> 0.9
> 1.0
> 1.1
> 1.2
> 1.3
> 1.4
> 1.5
> 1.6
> 1.7
> 1.8
> 1.9
> 2.0
> 2.1
> 2.2
> 2.3
> 2.4
> 2.5
> 2.6
> 2.7
> 2.8
> 2.9
> 3.0
> 3.1
> 3.2
> 3.3
> 3.4
> 3.5
> 3.6
> 3.7
> 3.8
> 3.9
>






More information about the Python-list mailing list