【问题标题】:Dynamically create a sum of functions动态创建函数总和
【发布时间】:2018-02-05 14:24:13
【问题描述】:

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

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

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


问题

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

除了作为超函数的表达式之外,我不使用子函数。所以我想知道是否可以跳过第一步,而是直接从任意大小的点集创建超级函数。以下是预期结果的示例:


示例

给定集合:[ point(2,1,4), point(3,2,1), point(1,4,3) ]
制作:

给定集合:[ point(4,2,1), point(3,5,6) ]
制作:


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

【问题讨论】:

  • 所以你想要一个构建数学函数的函数以便稍后调用它,对吗?
  • @Tzomas 是的,这就是计划。此外,数学函数不是符号函数,而是应该能够产生以整数或浮点数作为输入的输出。

标签: python-3.x function dynamic-programming factory


【解决方案1】:
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))

【讨论】:

  • 看起来不错。如果有适当的解释会更好。
  • 既然我要休息了,我在这里投个赞成票。希望我回来时会看到改进。祝你好运。
  • @romph 感谢您的解决方案。一个问题:我必须多次使用函数的总和,所以我可以做到不必每次都参考点集吗?
【解决方案2】:
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

【讨论】:

    猜你喜欢
    • 2015-07-17
    • 2019-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-17
    • 1970-01-01
    • 1970-01-01
    • 2021-02-16
    相关资源
    最近更新 更多