簡體   English   中英

使用遞歸函數在python中求和

[英]Summation in python using recursive function

我想計算下面的總和

在此輸入圖像描述

其中f_j,f_j是之前計算的q和q=sin(theta)函數, where theta varies[0,90] ,並且r_ij是我正在進行此計算的每兩個元素的相應距離。

我首先使用了sum()函數,但它沒有正常工作,因為它返回一個浮點數,但是當q正在改變而且它沒有求和它我期待一個數組!我已經放棄了它。

我的第二種方法是用於計算這個求和的遞歸函數,但是我得到了很多錯誤並且不知道我的代碼有什么問題,因為我的所有語法都是正確的,我不知道為什么我會一個接一個地得到錯誤或錯誤的值!

    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

但我不知道它是否給了我正確的總和,因為我最終得到的圖表遠非我的預期,並表明這個求和不應該是正確的。

Python中的遞歸是有限的。 無論如何我會嘗試求和。

請注意,在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.
...

軸參數告訴它僅僅是維度的總和。 這意味着,如果沿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等。

仍然不確定你的最終結果是什么。 但這里有一些起點。

使用它來加載位置,計算距離並將其放入數組中。

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數組,你可以通過利用數組乘法和sum的numpy版本來對求和進行向量化。 它允許您定義要匯總的軸。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM