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

Postby hrs » Tue Oct 29, 2013 9:27 pm

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.25
0.25
0.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.16666666666666677
0.16666666666666655
0.4999999999999999
0.8333333333333331
1.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

Postby hrs » Tue Oct 29, 2013 9:43 pm

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

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

Re: Floating point accuracy in custom range function

Postby micseydel » Wed Oct 30, 2013 1:31 am

Thanks for posting your solution instead of deleting the post! :)
Join the #python-forum IRC channel on irc.freenode.net!

Please do not PM members regarding questions which are meant to be discussed publicly. The point of the forum is so that others can benefit from it. We don't want to help you over PMs or emails.
User avatar
micseydel
 
Posts: 1223
Joined: Tue Feb 12, 2013 2:18 am
Location: Mountain View, CA


Return to General Coding Help

Who is online

Users browsing this forum: Bing [Bot], Google [Bot] and 2 guests