提高使用if-else语句编写的重叠分段函数的计算速度

问题描述

我有一个看起来像这样的函数

overlapping function

从许多.json文件的目录中读取m。

我为此编写的Python代码如下:

for i in os.listdir(PATH):
    if i.endswith(".json"):
    
        # Read in m value from json files 
        posterior_files = bilby.result.read_in_result(PATH + "/" + i)
        m = np.asarray(posterior_files.posterior['mass_1'].values)
        p = np.asarray(posterior_files.posterior['log_prior'].values)

        m = [] # one big float array per each json file 
        A = []
        B = []
        C = []

            
        for j in range(0,len(m)):
            if m1[j]<5. and m1[j]>10.:
                A = 0
            else:
                A = m**(-1.) # some algebraic expression

            if m1[j]<3. and m1[j]>10.:
                B = 0
            else:
                B = m**(-2.) # some algebraic expression

            if m1[j]<5. and m1[j]>10.:
                C = 0
            else:
                C = m**(-3.) # some algebraic expression

       num = 1.0/len(m) * np.sum((A+B)/np.exp(p))
       den = 1.0/len(m) * np.sum((C)/np.exp(p))

       factor = num/den
       print(factor)

(我省略了真实的代数表达式,因为它对问题本身并不重要。)

这段代码可以运行,但是问题是运行时间很长。有了实际的数据和表达式,花了一天的时间在超级计算机上运行。我需要重写它,以便花费更少的时间。

我尝试使用分段函数,但问题是条件重叠,这会导致其他错误

我将非常感谢您的任何建议!

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)