gpt4 book ai didi

c++ - 定义分段函数(例如多项式)

转载 作者:太空狗 更新时间:2023-10-29 23:06:10 27 4
gpt4 key购买 nike

在 C++ 中定义分段函数的最佳方法是什么,例如在使用样条曲线时需要?

例子:

        f1(x) if x from [0, 5)
f(x) = f2(x) if x from [5, 10)
f3(x) if x from [10, 20)

我目前的做法是这样的:

class Function
{
virtual double operator()( double x ) = 0;
}

class SomeFun : public Function
{
// implements operator() in a meaningful way
}

class PiecewiseFunction : public Function
{
// holds functions along with the upper bound of the interval
// for which they are defined
// e.g. (5, f1), (10, f2), (20, f3)
std::map< double, Function* > fns;

virtual double operator()( double x )
{
// search for the first upper interval boundary which is greater than x
auto it = fns.lower_bound( x );
// ... and evaluate the underlying function.
return *(it->second)(x);
}
}

我知道这种方法没有检查 x 是否在函数的整体边界内,比如上面例子中的 [0, 20),也许命名不是最好的 (Functionstd::function 等)。

有什么想法可以更聪明地做到这一点吗?该方法使用要在 std::map 中排序的键的属性。这与效率无关,更多的是关于简洁的设计。

切片

不完全是问题的一部分,但在其中一条评论中,提到了切片,您可以在这里阅读。

std::map unable to handle polymorphism?

我在上面的代码中更正了这个问题。

最佳答案

当前设计的一个问题是,它不允许最自然地被认为在某些区间或点(如 0)内未定义的函数,但有很多这样的函数,所以这是范围检查的另一个动机.此外,Function 需要替换为 Function*,这需要对语法进行一些其他更改。

class PiecewiseFunction : public Function
{
//Holds function and interval
std::map< std::pair<double,double>, Function* > fns;

double operator()( double x )
{
auto iter = std::find_if(fns.cbegin(), fns.cend(),
[=](const std::pair< std::pair<double,double>, Function*>& fn)
{
return x>=fn.first.first && x<fn.first.second;
});

if (iter == fns.end()) throw... //Or something
return (*iter->second)(x);
}
};

关于c++ - 定义分段函数(例如多项式),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16754413/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com