如何使用C中的表达式模板来实现符号微分++
Answer 1:
一般你想要的方式来表示你的符号(即编码例如表达模板3 * x * x + 42
),和一元函数,可以计算的衍生物。 希望你用C ++元编程非常熟悉,知道这意味着什么和需要,而是给你一个想法:
// This should come from the expression templates
template<typename Lhs, typename Rhs>
struct plus_node;
// Metafunction that computes a derivative
template<typename T>
struct derivative;
// derivative<foo>::type is the result of computing the derivative of foo
// Derivative of lhs + rhs
template<typename Lhs, typename Rhs>
struct derivative<plus_node<Lhs, Rhs> > {
typedef plus_node<
typename derivative<Lhs>::type
, typename derivative<Rhs>::type
> type;
};
// and so on
然后你会占用两个部分(表示和计算),这样,这将是方便使用。 例如derivative(3 * x * x + 42)(6)
可能意味着'计算的导数3 * x * x + 42
6在X'。
但是即使你不知道如何才能写出表达式模板,它需要用C来写一个元程序是什么++我不建议去一下这种方式。 模板元编程需要大量的样板,并可能很乏味。 相反,我向您天才Boost.Proto库,而这恰恰是旨在帮助(使用表达式模板)写EDSLs和这些表达式模板进行操作。 这也未必容易学习使用,但我发现,学习如何做到同样的事情,而无需使用较困难 。 下面介绍了可实际上理解并计算一个样本程序derivative(3 * x * x + 42)(6)
#include <iostream>
#include <boost/proto/proto.hpp>
using namespace boost::proto;
// Assuming derivative of one variable, the 'unknown'
struct unknown {};
// Boost.Proto calls this the expression wrapper
// elements of the EDSL will have this type
template<typename Expr>
struct expression;
// Boost.Proto calls this the domain
struct derived_domain
: domain<generator<expression>> {};
// We will use a context to evaluate expression templates
struct evaluation_context: callable_context<evaluation_context const> {
double value;
explicit evaluation_context(double value)
: value(value)
{}
typedef double result_type;
double operator()(tag::terminal, unknown) const
{ return value; }
};
// And now we can do:
// evalutation_context context(42);
// eval(expr, context);
// to evaluate an expression as though the unknown had value 42
template<typename Expr>
struct expression: extends<Expr, expression<Expr>, derived_domain> {
typedef extends<Expr, expression<Expr>, derived_domain> base_type;
expression(Expr const& expr = Expr())
: base_type(expr)
{}
typedef double result_type;
// We spare ourselves the need to write eval(expr, context)
// Instead, expr(42) is available
double operator()(double d) const
{
evaluation_context context(d);
return eval(*this, context);
}
};
// Boost.Proto calls this a transform -- we use this to operate
// on the expression templates
struct Derivative
: or_<
when<
terminal<unknown>
, boost::mpl::int_<1>()
>
, when<
terminal<_>
, boost::mpl::int_<0>()
>
, when<
plus<Derivative, Derivative>
, _make_plus(Derivative(_left), Derivative(_right))
>
, when<
multiplies<Derivative, Derivative>
, _make_plus(
_make_multiplies(Derivative(_left), _right)
, _make_multiplies(_left, Derivative(_right))
)
>
, otherwise<_>
> {};
// x is the unknown
expression<terminal<unknown>::type> const x;
// A transform works as a functor
Derivative const derivative;
int
main()
{
double d = derivative(3 * x * x + 3)(6);
std::cout << d << '\n';
}
文章来源: Symbolic differentiation using expression templates in C++