简体   繁体   English

Python中正弦波计算中的意外/意外结果

[英]Unexpected/Unwanted results in sine wave calculation in Python

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. 作为较大项目的一部分,我想更改波长类型模式中的某些值,而不是+1线性类型模式。

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. 明确地说,我不想尝试将它们绘制在图形或任何类似的图形上……我想使用这些值来控制我的Raspberry Pi的某些颜色强度。

Anyways, back to the issue at hand... 无论如何,回到眼前的问题...

I have the following python script: 我有以下python脚本:

#!/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? 我究竟做错了什么?

These values are not "way-out-there," they are consistent with zero to machine precision. 这些值不是“无处不在”,它们与零到机器精度是一致的。 Python typically has precision to 53 bits: Python通常具有53位的精度:

https://docs.python.org/2/tutorial/floatingpoint.html 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. 二进制表示形式对应于〜1e-16,这是您在正弦函数中应与零对应的值中看到的顺序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM