2017-02-23 130 views
-1

我最终想要绘制三个合并积分到其中每个积分评估z=np.linspace(1e+9,0)的Python - 功能不产生相同的二维阵列

enter image description here

import numpy as np 
import matplotlib.pyplab as plt 
import scipy as sp 
import scipy.integrate as integrate 

z = np.linspace(1e+9, 0, 1000) 
mass = 1000 
Omega_m0 = 0.3 
Omega_L0 = 0.7 
h = 0.7 


def FreeStreamLength(z, mass, Omega_m0, Omega_L0, h): 
    kb = 8.617e-5 ## kev K^-1 
    c = 3e+5 ## km/s 
    T0 = 2.7 ## K 
    T_uni = mass/kb 

    a = 1./(z+1.) 

    z_nr = T_uni/T0 - 1. ## redshift at non relativistic 
    a_nr = 1/(z_nr + 1.) ## scale factor at non relativistic 

    Omega_r0 = (4.2e-5)/h/h 
    a_eq = Omega_r0/Omega_m0 
    z_eq = 1/a_eq - 1 

    a1 = a[a <= a_nr] ## scale factor before particles become non-relativistic 
    a2 = a[a_nr <= a.all() <= a_eq] 
    a3 = a[a_eq <= a] 

    integrand = lambda x: 1./x/x/np.sqrt(Omega_m0/x/x/x + Omega_L0) 

epoch_nr = [ c/H0 *integrate.quad(integrand, 0, i)[0] for i in a1] 
epoch_nreq = [c/H0/a_nr * integrate.quad(integrand, a2, a_eq)[0] ] 
epoch_eq = [c/H0/a_eq * integrate.quad(integrand, i, 1)[0] for i in a3] 
return epoch_nr + epoch_nreq + epoch_eq 

z应该通过a阵列的特定部分,如此有效地,这些值应该相互关联。

对于return行我组合了所有的列表来为我的函数创建这个新的数组。

FSL = FreeStreamLength(z, mass, Omega_m0, Omega_L0, h) 

fig = plt.figure() 
ax = fig.add_subplot(111) 

ax.plot(z, FSL, color="blue", label=r"$z=0$") 
plt.show() 

我与ValueError: x and y must have same first dimension

为什么我的新名单不与名单,我以前还搭配回来了?

我相信它必须与我如何从传递的数组中迭代元素,然后才能在函数中定义被积函数。

+0

我无法运行脚本,因为没有定义'T_uni'和'T0' – gsmafra

+0

@gsmafra对不起,我编辑了导致它的不相关部分。所以再试一次。 – DarthLazar

+0

我仍然不能运行你的代码,而没有做出猜测和更正! – hpaulj

回答

0

我不知道你到底想要做什么,但是当你将一个布尔数组索引到python中的另一个数组时,你会得到一个包含布尔数组为True的元素的数组。

>>> import numpy as np 
>>> a = np.asarray([1,2,3]) 
>>> b = np.asarray([True,False,True]) 
>>> print(a[b]) 
array([1, 3]) 

这就是所发生的事情在这条线

a1 = a[a <= a_nr] ## scale factor before particles become non-relativistic 

而且,这里

epoch_nr + epoch_nreq + epoch_eq 

要添加三个列表(其中两个具有长度为1)。当你这样做,你得到这些名单追加,结果将有那些3所列出的长度总结:

>>> a = [1,2,3] 
>>> b = [1] 
>>> c = [1] 
>>> a + b + c 
[1, 2, 3, 1, 1] 
0

您是清楚地了解发生了错误,但我猜,在该xy错误信息对应于z,FSL输入到plot。你打印过这两个变量的形状吗?当你在这里,检查他们的dtype

我预计,从z = np.linspace(1e+9, 0, 1000)z是(1000,)浮点数。

但什么是FSL?你的函数的缩进是关闭的,但我猜测它是epoch_nr + epoch_nreq + epoch_eq。我会说3个数组的总和,但不,这些是列表。所以它是3个列表的连接。

那么这个清单的总长度是len(a1)+1+len(a3)

我们不应该通过你的代码猜测每一步发生的事情。这是你的工作。当您在numpy中遇到尺寸问题时,请在代码中的任何可疑点处开始打印形状。不要猜测形状应该是什么!验证它。


好吧,我跳过枪,试图运行你的代码。

a_nr <= a.all() <= a_eq应该做什么?

a2 = a[(a_nr <= a) & (a <= a_eq)] 

但使len(a2) 4和len(a3) 1,其搅乱epoch_nreq积分(与a2边界)。