功能设计

Function Design

本文关键字:功能设计      更新时间:2023-10-16

我有一个数组,包含场景中不同对象的位置。计算下一个移动步骤

我想建立一个这样的函数:

f(x) = 1/(x-pos1)^2 + 1/(x-pos2)^2 + ...
       ^term1         ^term2         ^term_n

我不知道场景中有多少个对象,所以我想在函数中为每个对象添加术语:

类似于:

for object in scene:
     add_one_term_to_the_function
return function

有办法编程吗?最好使用C++或Python。。。我只知道两种语言。。。

附言:答案是什么。。。但循环不是我想要的。这将是极其缓慢的。。因为每次我调用下一个事件时,它都会计算函数。。。但我只想计算一次。。。然后将事件传递给计算的"函数"。。。

为什么不循环它们?它不会比其他情况慢太多。

def f(x,poslist):
  v = 0
  for pos in poslist:
    v += 1/((x-pos)*(x-pos))
  return v

如果你真的想在python中做它,你可以这样做(但我认为它会很慢(

def addterm(f, pos):
  def g(x):
    return f(x)+1/((x-pos)*(x-pos))
  return g
def zero(x): return 0
f = zero
for pos in poslist:
  f=addterm(f, pos)

C++中没有真正的类似,因为C++没有闭包。人们可以模拟它,但它不会是一样的,然后你可以使用一个列表和一个循环。

function = lambda x : sum([1/(x-obj.pos)**2 for obj in scene])

然后你可以做

function(10);function(100);(等等(

当然,只需使用一个容器和一个循环:

#include <vector>
#include <cmath>
double f(double x, const std::vector<Position> & positions)
{
  double res = 0;
  for (std::vector<Position>::const_iterator it = positions.begin(); it != positions.end(); ++it)
  {
    res += std::pow(x - *it, -2);
  }
  return res;
}

我假设Position是一个可以转换为浮点数的类型。将位置集合作为第二个参数传递给函数。std::vector是C++中典型的容器,但如果您有特定的需求,还可以选择其他容器。