文章目录
本文代码:
Fourier级数和Taylor级数对原函数的逼近动画
级数是对已知函数的一种逼近,比较容易理解的是Taylor级数,通过多项式来逼近有限区间内的函数,其一般形式为
f ( x ) = ∑ n = 0 N a n x n f(x)=\sum_{n=0}^N a_nx^n f(x)=n=0∑Nanxn
其中最著名的应该是自然指数,根据其导数不变的特点,我们可以很容易得到其表达式
e x = ∑ n = 0 N x n n ! e^x=\sum_{n=0}^N \frac{x^n}{n!} ex=n=0∑Nn!xn
随着N的不断增加,其逼近过程如图所示

其中,Taylor级数的实现方法如下,除了exp函数之外,还包括sin和cos函数的Taylor级数。
def Taylor(x,funcType='exp',n=0):
func = {
'exp' : lambda x,n : x**n/fac(n),
'sin' : lambda x,n : (-1)**n*x**(2*n+1)/fac(2*n+1),
'cos' : lambda x,n : (-1)**n*x**(2*n)/fac(2*n)
}
return func[funcType](x,n)
绘图代码如下
def approxGif(num=30, funcType='exp'):
funcType = func if type(func)==str else 'auto'
if type(func)==str:
func = funcDict[func]
x = np.linspace(0,10,1000)
Y =func if type(func)==type(x) else func(x)
if method in ['Taylor','taylor']:
y = Taylor(x,funcType,0)
elif method in ['Fourier','fourier']:
y = Fourier(x,funcType,0)
num = range(num)
#画图初始化
fig = plt.figure()
ax = fig.add_subplot(111,autoscale_on=False,
xlim=(0,10),ylim=(min(Y)-0.5,max(Y)+0.5))
ax.plot(x,Y,color='g',lw=0.2)
ax.grid()
line, = ax.plot([],[],lw=0.5)
time_text = ax.text(0.1,0.9,'',transform=ax.transAxes)
# 动画初始化
def init():
line.set_data([],[])
time_text.set_text('level:'+str(0))
return line, time_text
# 动画迭代
def animate(n):
nonlocal y
y = Taylor(x,funcType,n) if n==0 else y+Taylor(x,funcType,n)
line.set_data(x,y)
time_text.set_text('level:'+str(n))
print(n)
return line, time_text
ani = animation.FuncAnimation(fig,animate,
num,interval=200,blit=False,init_func=init)
#ani.save(funcType+'.gif',writer='pillow')
plt.show()
Fourier级数也是本着相同的思维,只不过采用了不同频率的三角函数作为其空间中的基底。
对于以 2 π 2\pi 2π为周期的方波信号
f ( x ) = { 1 x ∈ [ 0 , π ) − 1 x ∈ [ − π , 0 ) f(x)=\left\{\begin{aligned} 1\quad &x \in[0,\pi)\\ -1\quad &x\in[-\pi,0) \end{aligned}\right. f(x)={1−1x∈[0,π)x∈[−π,0)
其Fourier级数为
f ( x ) = 4 π ∑ n = 0 N sin x 2 n + 1 f(x)=\frac{4}{\pi}\sum_{n=0}^N\frac{\sin x}{2n+1} f(x)=π4n=0∑N2n+1sinx
实现为
def Fourier(x,funcType='square',n=0):
func = {
'square' : lambda x,n : 4/np.pi*np.sin((2*n+1)*x)/(2*n+1),
'tri' : lambda x,n: np.pi/2 if n == 0 \
else -4/np.pi*np.cos((2*n-1)*x)/(2*n-1)**2,
'oblique': lambda x,n : 2*np.sin((n+1)*x)/(n+1)*(-1)**n
}
return func[funcType](x,n)
绘图代码为
def square(x):
x = np.mod(x,np.pi*2)
x[x>np.pi] = -1
x[x!=-1] = 1
return x
def tri(x):
return np.pi-np.abs(np.mod(x,2*np.pi)-np.pi)
funcDict = {
'exp':np.exp,
'sin':np.sin,
'cos':np.cos,
'square':square,
'tri':tri,
}
# func支持三种输入模式,即字符串,函数以及numpy数组
def approxGif(func='square',method='fourier',num=30):
funcType = func if type(func)==str else 'auto'
if type(func)==str:
func = funcDict[func]
x = np.linspace(0,10,1000)
Y =func if type(func)==type(x) else func(x)
if method in ['Taylor','taylor']:
y = Taylor(x,funcType,0)
elif method in ['Fourier','fourier']:
y = Fourier(x,funcType,0)
num = range(num)
#画图初始化
fig = plt.figure()
ax = fig.add_subplot(111,autoscale_on=False,
xlim=(0,10),ylim=(min(Y)-0.5,max(Y)+0.5))
ax.plot(x,Y,color='g',lw=0.2)
ax.grid()
line, = ax.plot([],[],lw=0.5)
time_text = ax.text(0.1,0.9,'',transform=ax.transAxes)
# 动画初始化
def init():
line.set_data([],[])
time_text.set_text('level:'+str(0))
return line, time_text
# 动画迭代
def animate(n):
nonlocal y
if method in ['taylor','Taylor']:
y = Taylor(x,funcType,n) if n==0 \
else y+Taylor(x,funcType,n)
elif method in ['fourier','Fourier']:
y = Fourier(x,funcType,n) if n==0 \
else y+Fourier(x,funcType,n)
pass
line.set_data(x,y)
time_text.set_text('level:'+str(n))
print(n)
return line, time_text
ani = animation.FuncAnimation(fig,animate,
num,interval=200,blit=False,init_func=init)
#ani.save(funcType+'.gif',writer='pillow')
plt.show()
如图所示

相应地三角波为
![]() | |
![]() |
上述只是给出了几个直观的例子,用以表明Taylor级数和Fourier级数的使用方法,从而让我们具备这种通过多项式或者三角函数来逼近已知函数的意识。而对于已知表达形式的函数 y = f ( x ) y=f(x) y=f(x),Taylor级数和Fourier级数都有导数或者积分的表示形式。
关闭。这个问题是opinion-based.它目前不接受答案。想要改进这个问题?更新问题,以便editingthispost可以用事实和引用来回答它.关闭4年前。Improvethisquestion我想在固定时间创建一系列低音和高音调的哔哔声。例如:在150毫秒时发出高音调的蜂鸣声在151毫秒时发出低音调的蜂鸣声200毫秒时发出低音调的蜂鸣声250毫秒的高音调蜂鸣声有没有办法在Ruby或Python中做到这一点?我真的不在乎输出编码是什么(.wav、.mp3、.ogg等等),但我确实想创建一个输出文件。
我想在一个没有Sass引擎的类中使用Sass颜色函数。我已经在项目中使用了sassgem,所以我认为搭载会像以下一样简单:classRectangleincludeSass::Script::FunctionsdefcolorSass::Script::Color.new([0x82,0x39,0x06])enddefrender#hamlengineexecutedwithcontextofself#sothatwithintemlateicouldcall#%stop{offset:'0%',stop:{color:lighten(color)}}endend更新:参见上面的#re
我正在尝试用ruby中的gsub函数替换字符串中的某些单词,但有时效果很好,在某些情况下会出现此错误?这种格式有什么问题吗NoMethodError(undefinedmethod`gsub!'fornil:NilClass):模型.rbclassTest"replacethisID1",WAY=>"replacethisID2andID3",DELTA=>"replacethisID4"}end另一个模型.rbclassCheck 最佳答案 啊,我找到了!gsub!是一个非常奇怪的方法。首先,它替换了字符串,所以它实际上修改了
我有一些代码在几个不同的位置之一运行:作为具有调试输出的命令行工具,作为不接受任何输出的更大程序的一部分,以及在Rails环境中。有时我需要根据代码的位置对代码进行细微的更改,我意识到以下样式似乎可行:print"Testingnestedfunctionsdefined\n"CLI=trueifCLIdeftest_printprint"CommandLineVersion\n"endelsedeftest_printprint"ReleaseVersion\n"endendtest_print()这导致:TestingnestedfunctionsdefinedCommandLin
这个问题在这里已经有了答案:关闭10年前。PossibleDuplicate:Pythonconditionalassignmentoperator对于这样一个简单的问题表示歉意,但是谷歌搜索||=并不是很有帮助;)Python中是否有与Ruby和Perl中的||=语句等效的语句?例如:foo="hey"foo||="what"#assignfooifit'sundefined#fooisstill"hey"bar||="yeah"#baris"yeah"另外,类似这样的东西的通用术语是什么?条件分配是我的第一个猜测,但Wikipediapage跟我想的不太一样。
什么是ruby的rack或python的Java的wsgi?还有一个路由库。 最佳答案 来自Python标准PEP333:Bycontrast,althoughJavahasjustasmanywebapplicationframeworksavailable,Java's"servlet"APImakesitpossibleforapplicationswrittenwithanyJavawebapplicationframeworktoruninanywebserverthatsupportstheservletAPI.ht
如何在Ruby中按名称传递函数?(我使用Ruby才几个小时,所以我还在想办法。)nums=[1,2,3,4]#Thisworks,butismoreverbosethanI'dlikenums.eachdo|i|putsiend#InJS,Icouldjustdosomethinglike:#nums.forEach(console.log)#InF#,itwouldbesomethinglike:#List.iternums(printf"%A")#InRuby,IwishIcoulddosomethinglike:nums.eachputs在Ruby中能不能做到类似的简洁?我可以只
华为OD机试题本篇题目:明明的随机数题目输入描述输出描述:示例1输入输出说明代码编写思路最近更新的博客华为od2023|什么是华为od,od薪资待遇,od机试题清单华为OD机试真题大全,用Python解华为机试题|机试宝典【华为OD机试】全流程解析+经验分享,题型分享,防作弊指南华为o
我想解析一个已经存在的.mid文件,改变它的乐器,例如从“acousticgrandpiano”到“violin”,然后将它保存回去或作为另一个.mid文件。根据我在文档中看到的内容,该乐器通过program_change或patch_change指令进行了更改,但我找不到任何在已经存在的MIDI文件中执行此操作的库.他们似乎都只支持从头开始创建的MIDI文件。 最佳答案 MIDIpackage会为您完成此操作,但具体方法取决于midi文件的原始内容。一个MIDI文件由一个或多个音轨组成,每个音轨是十六个channel中任何一个上的
本文主要介绍在使用Selenium进行自动化测试或者任务时,对于使用了iframe的页面,如何定位iframe中的元素文章目录场景描述解决方案具体代码场景描述当我们在使用Selenium进行自动化测试的时候,可能会遇到一些界面或者窗体是使用HTML的iframe标签进行承载的。对于iframe中的标签,如果直接查找是无法找到的,会抛出没有找到元素的异常。比如近在咫尺的例子就是,CSDN的登录窗体就是使用的iframe,大家可以尝试通过F12开发者模式查看到的tag_name,class_name,id或者xpath来定位中的页面元素,会抛出NoSuchElementException异常。解决