使用递归函数在python中求和

时间:2014-02-16 15:48:14

标签: python function recursion numpy scipy

我正在尝试计算以下总和

enter image description here

其中f_j,f_j是之前计算的q函数和q=sin(theta) where theta varies[0,90],而r_ij是我正在进行此计算的每两个元素的相应距离。

我最初使用了sum()函数,但它不能正常工作,因为它返回一个浮点数,但是当q正在改变并且没有它的总和我期待一个数组!Ergo我给了它起来。

我的第二种方法是用于计算此求和的递归函数,但是我得到了很多错误并且不知道我的代码有什么问题,因为我的所有语法都是正确的,我不知道为什么我会得到错误或错误的值一个接一个!

    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()

错误:

RuntimeError: maximum recursion depth exceeded while calling a Python object

+这个问题与之前提到的递归求和问题不重复,因为我检查了它们,无法找到解决问题的方法。


我也尝试了这个功能

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

但是我不知道它是否给了我正确的总和,因为我最终得到的图表远非我的预期,并表明这个求和不应该是正确的。

2 个答案:

答案 0 :(得分:1)

Python中的递归是有限的。无论如何我会尝试求和。

请注意,在Numpy的和函数中,您有两个参数:

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.
...

轴参数告诉它仅加上维度的总和。这意味着,如果您沿着qj轴求和,您仍然可以在q轴上得到矢量结果。

你应该有类似的东西。

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.

这里,np.krons给你

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

和求和

array([124, 248, 372])

每行的单个元素。

您可以轻松地将其概括为包含f_i(q)(相同结构的2D数组),添加sin等。

答案 1 :(得分:1)

仍然不确定你的最终结果是什么。但这里有一些起点。

使用此方法加载位置,计算距离并将其放入数组中。

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]

如果你可以制作f_jf_i的数组,你可以利用数组乘法和和的numpy版本来对总和进行矢量化。它允许您定义要汇总的轴。