## Floating point accuracy in custom range function

This is the place for queries that don't fit in any of the other categories.

### Floating point accuracy in custom range function

Modelled after this idea of tnknepp (thanks!) I came up with the following function:
Code: Select all
`>>> def sample_range(start, stop, sample_rate):...     step = 1. / sample_rate...     while start < stop:...             yield start + 0.5 * step...             start += step`

This works fine for 1, 2, 4 and 5. Example of expected output (I removed a.next() for shortness):
Code: Select all
`>>> a = sample_range(-1,1,2)-0.75-0.250.250.75`

However, for a sample rate of 3 I get this:
Code: Select all
`>>> a = sample_range(-1,1,3)-0.8333333333333334-0.5000000000000001-0.166666666666666770.166666666666666550.49999999999999990.83333333333333311.1666666666666665`

I figured out that this must be due to floating point (in)accuracy. An unclean fix would be:
Code: Select all
`>>> def sample_range(start, stop, sample_rate):...     step = 1. / sample_rate...     while start + 0.000001 < stop:...             yield start + 0.5 * step...             start += step`

but that's not good enough. Is there a clean way to deal with this?
hrs

Posts: 86
Joined: Thu Feb 07, 2013 9:26 pm

### Re: Floating point accuracy in custom range function

Oh, nevermind. The obvious solution is:
Code: Select all
`>>> def sample_range(start, stop, sample_rate):...     step = 1. / sample_rate...     start += 0.5 * step...     while start < stop:...             yield start...             start += step`

hrs

Posts: 86
Joined: Thu Feb 07, 2013 9:26 pm

### Re: Floating point accuracy in custom range function

Join the #python-forum IRC channel on irc.freenode.net for off-topic chat!

Please prefer not to PM members. The point of the forum is so that anyone can benefit. We don't want to help you over PMs/emails/Skype chats that others can't benefit from

micseydel

Posts: 2036
Joined: Tue Feb 12, 2013 2:18 am
Location: Mountain View, CA