对参数函数求和

时间:2016-06-16 10:33:51

标签: python function numpy matplotlib

我正在处理这样的参数函数:

Parametric function

并且理想情况下我想对重复的x轴求和,如示例所示。也就是说,对于x~4.75,我看到函数可以是0.04,0.06或0.16,我想在0.06 + 0.04 + 0.16 = 0.26的总和上加一个点。我需要为每一点做到这一点,这样我就可以构造一个函数,它是参数的一种“投影”。任何人都知道如何在Python中做到这一点?

1 个答案:

答案 0 :(得分:1)

看一下例子:

import numpy as np
import matplotlib.pyplot as plt

# set x, y
x = np.arange(-3.,3.,.1)
N = x.size
x[10:13] = x[10]
y = x ** 3 + np.random.rand(N)

# plot curve
fig, ax = plt.subplots()
plt.plot(x,y,'b-')
curve = ax.lines[0]

# get data of plotted curve
xvalues = curve.get_xdata()
yvalues = curve.get_ydata()

# get y for given x 
indexes = np. where(xvalues == x[10]) 
# test print
print xvalues[indexes] 
print yvalues[indexes]
print "Sum of y(x) = ",np.sum(yvalues[indexes]) , " where x = ", x[10]

# define markers
xm = []
ym = []

for x1 in x:
    indexes = np.where(xvalues == x1) 
    print x1, yvalues[indexes]
    if len(yvalues[indexes]) > 1:
        xm += [xvalues[indexes],]
        ym += [np.sum(yvalues[indexes]),]

plt.plot(xm, ym, linestyle = 'None', marker='o', color='g')

plt.show()

测试输出:

x: [-2. -2. -2.]
y: [-7.0936372  -7.42647923 -7.56571131]
Sum of y(x) =  -22.0858277351  where x =  -2.0

enter image description here