简体   繁体   English

使用递归函数在python中求和

[英]Summation in python using recursive function

I am trying to calculate below summation 我想计算下面的总和

在此输入图像描述

where f_j,f_j are functions of q calculated before and q=sin(theta) where theta varies[0,90] , and r_ij is the respective distance bewteen each two elements I am doing this calculation for. 其中f_j,f_j是之前计算的q和q=sin(theta)函数, where theta varies[0,90] ,并且r_ij是我正在进行此计算的每两个元素的相应距离。

I used the sum() function at first but it didn't work proberly as it returns a float number, but as q is changing and there's no summation for it I'm expecting an array!Ergo I gave it up. 我首先使用了sum()函数,但它没有正常工作,因为它返回一个浮点数,但是当q正在改变而且它没有求和它我期待一个数组!我已经放弃了它。

My second approach was recursive function for calculating this summation,but I get so many errors and have no idea what is wrong with my code as I thing all the syntaxes are correct and I have no idea why I get errors or wrong values one after another! 我的第二种方法是用于计算这个求和的递归函数,但是我得到了很多错误并且不知道我的代码有什么问题,因为我的所有语法都是正确的,我不知道为什么我会一个接一个地得到错误或错误的值!

    theta=arange(radians(0.5), radians(40.010), radians(0.03))
    q=sin(theta) 

    f_q_1= 2*exp(-3*pow(q,2))+4*exp(-5*pow(q,2))+1.95
    f_q_2=...
    .
    f_q_i(or j).

    atom_positions= open('coordinates.txt','r')

    lines = atom_positions.readlines()
    for i in range(0, len(lines)):
        line = lines[i]
        values = line.split(" ")
        for j in range(0,len(lines)):
         if j<>i: 
          nextLine = lines[j]
          nextLineValues = nextLine.split(" ")

           r =sqrt((float(values[5])-float(nextLineValues[5]))**2 + (float(values[6])
          -float(nextLineValues[6]))**2+(float(values[7])-float(nextLineValues[7]))**2)

            line_len = len(lines)
            def I_tot(line_len,i,f_i,f_j,r):
             I=0
             if i<line_len:
                I=I+(f_i*f_j*sin(q*r)/(q*r))
                return I + I_tot(line_len,i,f_i,f_j,r)
             else:
                return I
else:

     plot(2*theta,I_tot)
     show()
    atom_positions.close()

error: 错误:

RuntimeError: maximum recursion depth exceeded while calling a Python object

+This question is not a duplicate of recursive summation questions asked here before, As I checked them and couldn't find a solution to my problem. +这个问题与之前提到的递归求和问题不重复,因为我检查了它们,无法找到解决问题的方法。


I have also tried the function 我也试过这个功能

def I_tot():
       I=0
       for i in range(0,len(lines)):
          I=I+(f_i*f_j*sin(q*r)/(q*r))

       return I

But I have no idea whether it gives me the correct summation or not, because the graph I get in the end is far from my expectation and indicates that this summation should not be correct. 但我不知道它是否给了我正确的总和,因为我最终得到的图表远非我的预期,并表明这个求和不应该是正确的。

Recursion in Python is limited. Python中的递归是有限的。 I would try summation anyway. 无论如何我会尝试求和。

Note that in Numpy's sum function, you have two parameters: 请注意,在Numpy的sum函数中,您有两个参数:

def sum(a, axis=None, dtype=None, out=None, keepdims=False):
    """
    Sum of array elements over a given axis.

    Parameters
    ----------
    a : array_like
        Elements to sum.
    axis : None or int or tuple of ints, optional
        Axis or axes along which a sum is performed.
        The default (`axis` = `None`) is perform a sum over all
        the dimensions of the input array. `axis` may be negative, in
        which case it counts from the last to the first axis.
...

The axis parameters tell it to sum in only sum of the dimensions. 轴参数告诉它仅仅是维度的总和。 Meaning, if you sum along the q and j axis, you can still have a vector result in the q axis . 这意味着,如果沿qj轴求和,则仍然可以在q轴上得到矢量结果。

You should have something similar to that. 你应该有类似的东西。

import numpy as np
qs = np.array([1,2,3]) #Generate sum qs.
r = np.array([[11,21, 41,51]]) #the r_ij compnent. as a 1D vector 
                               #(you can get it using reshape() )

np.kron(qs,r.T).sum(axis=0) #a vector containing sum(q*r) for each q.

Here, np.krons gives you 在这里,np.krons给你

array([[ 11,  22,  33],
       [ 21,  42,  63],
       [ 41,  82, 123],
       [ 51, 102, 153]])

and the summation gives 并且总和给出了

array([124, 248, 372])

A single element for each line. 每行一个元素。

You can easily generalize it to include f_i(q) (a 2D array of the same structure), add sin , etc. 您可以轻松地将其概括为包含f_i(q) (相同结构的2D数组),添加sin等。

still not sure what your end result is gonna be. 仍然不确定你的最终结果是什么。 But here are some starting points. 但这里有一些起点。

Use this to load inn the positions, calculate the distances and put it in a array. 使用它来加载位置,计算距离并将其放入数组中。

import numpy as np
from scipy.spatial import distance
values = np.genfromtxt('coordinates.txt', dtype=float, usecols=[5,6,7])
r_ij = distance.squareform(distance.pdist(xyz))
nPositions = r_ij.shape()[0]

If you can make arrays of f_j and f_i , you can probably vectorize the summation, by utilizing array multiplication and the numpy version of sum. 如果你可以创建f_jf_i数组,你可以通过利用数组乘法和sum的numpy版本来对求和进行向量化。 which allows you to define what axis to sum over. 它允许您定义要汇总的轴。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM