动态创建函数总和

Dynamically create a sum of functions

我在处理程序中的必要元素时遇到问题:

给定一组形式为 ( x, y, a ) 的点,产生形式为的高斯函数:

f(x,y)

...从每个点。然后生成一个函数,它是所有创建的子函数的总和。


问题

目前,我要做的是从每个点创建一个函数并将其附加到列表中。然后我创建了一个新函数,它是这个函数列表中各项的总和。这按预期工作,但我想要一种更有效的方法。

除了 super-function 的表达式外,我不使用 sub-functions。所以我想知道是否可以跳过第一步,而是直接从任意大小的点集创建 super-function 。以下是预期结果的示例:


例子

给定集合:[ point(2,1,4), point(3,2,1), point(1,4,3) ]
生产:Ex1

给定集合:[ point(4,2,1), point(3,5,6) ]
生产:Ex2


注意:请记住,我所说的集合实际上只是列表。

from math import exp, pow

class AllPoint:
    def __init__(self, array):#give the set of points
        self.points = array

    def applyGaussianFunction(self, x, y): #for each point sum the gaussian function result
        if(len(self.points) == 0): #if there is no point launch an error
            raise AssertionError("no points in the array")
        allSum = 0
        for p in self.points: #doing the sum of every gaussian function
            allSum += p.gaussianFunction(x, y);
        return allSum

class Point: #create an object named point (the keywork self means the object in question #this)
    def __init__(self, x, y, a): #this object posseed three attributes (x, y, a) 
        self.x = x
        self.y = y
        self.a = a

    def gaussianFunction(self, x, y): #each point can apply the gaussian function on himself so each point can call her by doing ThePoint.gaussianFunction(x, y)
        return self.a * exp(-pow(x - self.x, 2)-pow(y - self.y, 2)) #the formula

p1 = Point(4, 2, 1)
p2 = Point(3, 5, 6)
points = AllPoint([p1, p2])
print(points.applyGaussianFunction(3, 4))
from math import exp, pow
from collections import namedtuple

Point = namedtuple('Point', 'x y a')

def sum_function(x, y, points):
  # use list comprehension to loop over the points and calculate the gaussian, 
  # then use the sum function to compute the sum of the list elements
  return sum([p.a * exp(-pow(x - p.x, 2) - pow(y - p.y, 2)) for p in points])

p1 = Point(4,2,1)
p2 = Point(3,5,6)
a_certain_set_of_points = (p1, p2)

要回答有关如何避免两次引用特定点集的问题,您可以使用 lambda:

a_certain_sum_function = lambda x,y : sum_function(x, y, a_certain_set_of_points)
print(a_certain_sum_function(1, 2))

PS:我会给出这个答案作为对 romph post 的评论,但我似乎没有足够的代表点数来这样做 :o