如何在scipy / python中实现涉及两个参数积分的函数的绘图?

时间:2015-05-13 05:24:32

标签: python numpy matplotlib plot scipy

我试图计算并绘制积分函数,其积分是两个参数的函数,其上限也是一个参数的函数。

即,使用下限a和上限Integrate(F(x,y)dy)绘制f(x)

当我使用python main4.py运行程序时,收到以下错误消息:

> Traceback (most recent call last):
  File "main4.py", line 46, in <module>
    value[idx],errorlow = quad(Zmomentlow1, a, alpha(p), args = (p)) + quad(Zmomentlow2, alpha(p), b, args = (p))
ValueError: too many values to unpack

我正在使用Python 2.7.8。

在其他网站上与我的一位朋友协商后,我能够编辑代码的第46行。此更正使代码可以在没有任何错误消息的情况下运行,如上所述。但是,这次,结果图是空的,意味着所有y值都为零,我没有得到附加到下面帖子的预期图(通过Mathematica获得。)snapshot1.png

       """
main7.py
Demonstrates using the arg parameter to 
pass parameters to the integrand function 
when using the quad() function.
"""

# import the needed modules
import numpy as np
import matplotlib.pyplot as plt
from pylab import *
from scipy.integrate import quad

# define the integrand function 
def F(p, x):
  return 4445.935*np.power(143.753 + 19 * np.log(p/x), -1, dtype=np.int16) * np.power(x, 0.2354424, dtype=np.int16) * np.power(1-np.power(x, 0.375, dtype=np.int16), 5.55373, dtype=np.int16)
def Zmomentlow1(p, x):
  return 2*np.power(x, 2)*F(p, x)
def Zmomentlow2(p, x):
  return 2*np.power(x, 1.7)*F(p, x)
def Zmomenthigh(p, x):
  return 2*np.power(x, 2)*F(p, x)

def Zmoment(p):
  for p, ep in enumerate(p): #make Zmoment(enegrgy) values
    if ep>0 and ep<=c:
      Zmoment[p] = Zmomentlow1 + Zmomentlow2
    elif ep>c:
      Zmoment[p] = Zmomenthigh

# set the parameters
c = 5.0E6 # the energy corresponding to the knee of the cosmic ray flux
a = 0   # lower limit of first integration of low-energy domain
b = 1   # upper limit of second integration of low-energy domain
N = 1000 # number of alpha values to use in integrations

def alpha(p):
        return p/c

p_ary = np.linspace(1.0E2,1.0E11,N) # create an array of values of energy
value = zeros(N)            # create an array to store results of integrations

# do the integrations low1, low2 and high
idx = 0
for p in p_ary:
    value[idx],errorlow = map(sum, zip(quad(Zmomentlow1, a, alpha(p), args = (p,)), quad(Zmomentlow2, alpha(p), b, args = (p,))))
   # value[idx], errorlow = quad(Zmomentlow1, a, alpha(p), args = (p)) + quad(Zmomentlow2, alpha(p), b, args = (p))
    value[idx], errorhigh = quad(Zmomenthigh, a, b, args = (p,))
    idx = idx + 0.001

# plot the result
plt.figure(1)
plt.clf()
plt.xscale('log')
plt.plot(p_ary,value)
plt.ylim([-0.01,0.01])


# note the new syntax for the xlabel() and title() commands
# that allows the use of LaTeX commands
xlabel('energy [GeV]') 
ylabel('Zmoment')
title('Plot of Z-moment vs. Energy') 
plt.show()
plt.savefig('Figure1')

0 个答案:

没有答案