在我的计划中,我很难找到一个必要的元素:
给定形式的一组点( x,y,a)产生形式的高斯函数:
..。从每一点。然后生成一个函数,该函数是所创建的所有子函数的总和。
问题
目前,我要做的是从每个点创建一个函数,并将其附加到列表中。然后,我创建一个新函数,它是这个函数列表中项的总和。这如预期的那样工作,但我想要一个更有效的方法。
除了作为超级函数的表达式外,我不使用子函数。所以我想知道是否可以跳过第一步,而直接从任意大小的点创建超级函数。以下是预期结果的例子:
示例
给定集合:点(2,1,4),点(3,2,1),点(1,4,3)
产生:
给定集合:点(4,2,1),点(3,5,6)
产生:
注意事项:请记住,我所称的集合实际上只是列表。
发布于 2018-02-05 14:49:55
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))
发布于 2018-02-05 15:32:12
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帖子的评论,但我似乎没有足够的代表点来这样做:o
https://stackoverflow.com/questions/48624696
复制相似问题