如果有条件,请在python中分配错误的值

时间:2019-10-07 06:39:46

标签: python loops if-statement conditional-statements integrate

更新:

检查了建议的解决方案,没有用。但是缩小了问题的范围。因此,如果人们可以透露一些信息,请在下面发布。

def X_he_z3(z):
    flag = -1 
    if z <=3.0 :  # z<3
        #x_he=1.
        flag = 1

    else:      
        flag = 0 
        #print flag
    if flag == 0 :
        X_he_z3.Xe_He_II = 1.
    else :
        X_he_z3.Xe_He_II = 0.
    return flag 

运行:

z = np.linspace(0,6,1000)
s = 1000
X  = []
X2 = []
f = []
one = np.ones(s)
for i in z:
    f.append(X_he_z3(i)) # Returns flag
    X.append(X_he_z3.Xe_He_II)

plt.plot(z,X,'*') # He_II

enter image description here

plt.plot(z,f,'*',c='g')

enter image description here  标志在[0][1]范围内具有适当的值。因此,我想问题是如何将这些标志值调用到变量中造成一些混乱。有什么建议吗?


原始问题

这是我的代码,调用函数X_he_z(z)进行集成。 函数内部有一个if条件。在它下面有一个阶跃函数的表示。如果z < 3 ==> X_he_z.Xe_He_II = 0. else if z > 3 ==> X_he_z.Xe_He_II = 1.

import pandas as pd
import numpy as np
from scipy import integrate
import matplotlib.pyplot as plt 

def X_he_z(z):
    global omega_m
    omega_m = 0.3
    global Y;global x_he;#global Xe_He_II;global Xe_He_III;
    Y = 0.25

    X_he_z.x_h = 1.  # X_e_H ~ 1 for z<6 
    if (z - 3.0) < 0.00 :  # z<3
        #x_he=1.
        X_he_z.Xe_He_II = 0. # ** This is the line in question**
        X_he_z.Xe_He_III= 1.
        x_he = (X_he_z.Xe_He_II + 2.*X_he_z.Xe_He_III)

    elif (z - 3.0) > 0.00:       
        X_he_z.Xe_He_II = 1. # ** This is the line in question**
        X_he_z.Xe_He_III= 0.
        x_he = (X_he_z.Xe_He_II + 2.*X_he_z.Xe_He_III)

    #print 'z = %s, X_He_III = %.2f'%(z,Xe_He_III)
    X_he_z.x_he  =x_he
    X_z = ((1.-Y)*X_he_z.x_h + (1./4.)*(Y)*x_he)
    X_he_z.fe=X_z

    Num = X_he_z.fe*(1.+z)
    Den = (omega_m*((1.+z)**3.)+(1.-omega_m))**(0.5)
    I = Num/Den
    X_he_z.G = [I,X_he_z.fe,X_he_z.Xe_He_II,X_he_z.Xe_He_III,X_he_z.x_h,X_he_z.x_he]
    #print G
    #print I
    return I 

# Running the code + Integration

z = np.linspace(0,6,500)
s = 500
Dm = []
X  = []
one = np.ones(s)
for i in z:
    #print 'z ',i
    t = X_he_z(i)
    Dm.append(integrate.quad(X_he_z,0,i))
    X.append(X_he_z.G)
    # Returns in order : 
    # I, fe, He_II, He_III, H, He

Dm = pd.DataFrame(Dm,columns=['DM','Int_error']) 
Dm['z'] = z
Dm['H']= pd.DataFrame(X)[4]
Dm['He']= pd.DataFrame(X)[5]
Dm['HeII']= pd.DataFrame(X)[2]
Dm['HeIII']= pd.DataFrame(X)[3]
Dm['fe']= pd.DataFrame(X)[1]

本篇文章的其余部分不是必需的。我希望  X_he_z.Xe_He_II的值具有阶跃函数,如附图所示(忽略Y-axis的值), How I expect the He_II to behave in the z-range as x-axis我如何期望He_IIz-range中表现为x-axis

但是,如果我查看这些值,我会看到这是这样的: The black marked dots in the lower right are a surprise to me and I can't understand how. 右下角的黑色圆圈点让我感到惊讶,我不知道该怎么做。

结果相应的值有误,进入集成调用。我需要对底部的这几个点进行修复。

还可以在输出文件上检查结果:

enter image description here 如果我们检查line 444,,我们将看到第三列,即z值,而z > 3 (= 5.3146)6th列代表He_II,应为{{1} }处于上面代码的else条件中,但是它给出1的含义是在第一种情况下,即if块。为什么会这样?

1 个答案:

答案 0 :(得分:1)

elif ...:行更改为else:,您将不会再看到创建的问题。