## 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

Thanks for posting your solution instead of deleting the post! :)
Due to the reasons discussed here we will be moving to python-forum.io on October 1, 2016.

This forum will be locked down and no one will be able to post/edit/create threads, etc. here from thereafter. Please create an account at the new site to continue discussion.

micseydel

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

Return to General Coding Help

### Who is online

Users browsing this forum: Google [Bot] and 9 guests