0

As part of a larger project, I want to change some values in a wave length-type pattern, rather than a +1 linear-type pattern.

To be clear, I have no desire to try to plot these on a graph or anything of the sort... I want to use these values to control some color intensity through my Raspberry Pi.

Anyways, back to the issue at hand...

I have the following python script:

#!/usr/bin/python
from math import *
Fs=8000
f=500
i=0
while i<50:
    print ( sin(2*pi*f*i/Fs) )
    i+=1

Which gives me the following output (truncated):

0.0
0.382683432365
0.707106781187
0.923879532511
1.0
0.923879532511
0.707106781187
0.382683432365
1.22464679915e-16
-0.382683432365
-0.707106781187
-0.923879532511
-1.0
-0.923879532511
-0.707106781187
-0.382683432365
-2.44929359829e-16
0.382683432365
0.707106781187
0.923879532511
1.0

As you can see, every now and again there's a value that's just way out there:

1.22464679915e-16

-2.44929359829e-16

3.67394039744e-16

-4.89858719659e-16

2.38868023897e-15

-7.34788079488e-16

Why am I getting these strange results? How I avoid these way-out-there values? What am I doing wrong?

Rohan Khude
  • 4,455
  • 5
  • 49
  • 47
Jon M
  • 3
  • 2
  • Probably the "pi" constant is a float: https://en.wikipedia.org/wiki/Floating_point – Welbog Nov 30 '16 at 19:28
  • 1
    Those values aren't "way out there", they're very nearly 0.0. The reason they're not exactly zero is [floating point isn't always exact](http://stackoverflow.com/questions/588004/is-floating-point-math-broken). – Mark Ransom Nov 30 '16 at 19:36
  • Use `for i in range(50): print (16 + sin(2*pi*f*i/Fs) ) -16` to cut off the last bits with the rounding noise. – Lutz Lehmann Nov 30 '16 at 20:03

1 Answers1

1

These values are not "way-out-there," they are consistent with zero to machine precision. Python typically has precision to 53 bits:

https://docs.python.org/2/tutorial/floatingpoint.html

The binary representation for this corresponds with ~1e-16, which is the order you are seeing in the values that should correspond with zero in your sine function.

kiliantics
  • 1,148
  • 1
  • 8
  • 11