功能设计
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++中典型的容器,但如果您有特定的需求,还可以选择其他容器。
相关文章:
- 询问在设计我的手臂模拟器功能表示格式1
- 设计模式,以避免不必要地添加抽象函数以适应新功能
- C++功能设计
- 界面设计:超载功能的安全性采用字符串和字符阵列
- 有没有办法在我的通用功能路由器设计中支持"常量引用"作为功能签名参数?
- 用于存储由第一个功能创建的指针的设计模式将在以后使用
- 如何正确设计和实施功能模板专业化
- 虚拟功能设计问题
- 功能超载类设计
- C++虚拟功能与设计模式
- 委派模板成员功能的良好设计
- C++:类功能子集的推荐设计模式
- 如何为不同的硬件功能设计具有独特实现的过程
- if/else vs虚拟功能:设计性能
- 设计一个好的C++包装器类,它包装了多个功能
- 专门为一个私人班级设计一个功能
- 工厂设计模式中的纯虚拟功能错误
- 功能原型设计会影响性能吗
- 功能设计决策
- 功能设计