开发者

Function Design

I have an array contanining the position of the different objects in my scene. To calculate the next movement step

I want to build a function like this:

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

I don't know how many objects are in my scene so I want to add terms in the function for each objects:

something like:

for object in scene:
     add_one_term_to_the_function
return function

is there a way to program this? Preferably 开发者_开发知识库in C++ or Python... the only two languages I know...

PS: thx for the answers... but a loop is not what I'm looking for. This would be extremly slow.. because it will calculate the function everytime I call a next event... but I want to calculte it only once... and then pass the events to the calculated "function"...


Why not loop over them? It's not going to be very much slower than otherwise.

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

If you really want to do it in python you can do it like this (but I beleive it's going to be very slow)

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)

There is no real analogue in C++, because C++ doesn't have closures. One could simulate it, but it won't be the same, and then you could use a list and a loop instead anyway.


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

then you can do

function(10);function(100); (and so on)


Sure, just use a container and a loop:

#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;
}

I assume that Position is a type that's convertible to a floating point number. You pass a collection of positions as the second argument to the function. std::vector is the prototypical container in C++, but there are others to choose from if you have specific needs.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜