如何在Python 3中绘制具有两个变量的求和 [英] How to plot a summation with two variables in Python 3

查看:55
本文介绍了如何在Python 3中绘制具有两个变量的求和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个函数并使用pyplot很好地绘制它.
自身的功能如下所示:

I would like to make a function and use pyplot to plot it nicely.
The function it self looks like this:

我的任务是为x在[-3pi,3pi]范围内的k = [2、4、6、8、10]绘制C.我也想在同一窗口中绘制cos(x).

I am tasked with plotting C for k = [2, 4, 6, 8, 10] for x in range [-3pi, 3pi]. I also want to plot cos(x) in the same window.

还有动画的方法吗?

到目前为止,我的代码是:

my code so far is :

import numpy as np
import matplotlib.pyplot as plt
import math 
n=0;
def C_series(n):
    return (((-1)**n)*x**(2*n)) / math.factorial(2*n)

C_func = np.vectorize(C_series)
x = np.arange(-3*math.pi, 3*math.pi, 5.0)
k = np.arange(2, 10, 2)
T = C_func(n)
plt.plot(T, k)

有人能给我关于我做错事情的任何指示吗?我并不是说要成为一个教程,我得到了一些苛刻的评论,但我希望现在我想抢苹果.

can anyone give me any pointers as to what I am doing wrong? I did not mean for this to be a tutorial, and I got some harsh comment, but I hope that now I am trying to grab the apple.

推荐答案

x和k必须是函数的输入,为简化任务,我们使用meshgrid创建了一个网格,然后在一个方向上添加,我们将获得轮廓每个k的曲线.

x and k must be the input of your function, to simplify the task we create a mesh with meshgrid and then add in one direction and we will obtain the profile of the curve for each k.

import numpy as np
import matplotlib.pyplot as plt
import math 
from scipy import misc


def C_series(x, k):
    n = np.arange(k)
    X, N = np.meshgrid(x, n)
    val =(((-1)**N)*X**(2*N)) / misc.factorial(2*N)
    return np.sum(val, axis=0)

x0 = -3*math.pi
xf= 3*math.pi

x = np.linspace(x0, xf, 100)

plt.plot(x, np.cos(x))    
for k in [2, 4, 6, 8, 10]:
    plt.plot(x, C_series(x, k), label=str(k))

plt.show()

屏幕截图:

对于 x0 = -1 xf = 1

这篇关于如何在Python 3中绘制具有两个变量的求和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆