首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Boost自动判别失败的应用

Boost自动判别失败的应用
EN

Stack Overflow用户
提问于 2022-03-10 11:41:03
回答 1查看 142关注 0票数 0

我想使用boost的自动关闭功能来计算一个复杂函数的二阶导数。

在boost help中,我可以查看以下示例:

代码语言:javascript
复制
#include <boost/math/differentiation/autodiff.hpp>
#include <iostream>

template <typename T>
T fourth_power(T const& x) {
    T x4 = x * x;  // retval in operator*() uses x4's memory via NRVO.
    x4 *= x4;      // No copies of x4 are made within operator*=() even when squaring.
    return x4;     // x4 uses y's memory in main() via NRVO.
}

int main() {
    using namespace boost::math::differentiation;

    constexpr unsigned Order = 5;                  // Highest order derivative to be calculated.
    auto const x = make_fvar<double, Order>(2.0);  // Find derivatives at x=2.
    auto const y = fourth_power(x);
    for (unsigned i = 0; i <= Order; ++i)
        std::cout << "y.derivative(" << i << ") = " << y.derivative(i) << std::endl;
    return 0;
}

我想利用这种可能性在我的课堂结构中计算一个导数,但我不明白怎么回事。下面是我的.cxx文件的一个简化代码示例。我有一个参数方程,它被分离成两个函数来得到x和y坐标。半径是一个成员变量。我要计算这个参数方程在phi位置的二阶导数。

代码语言:javascript
复制
#include <boost/math/differentiation/autodiff.hpp>

double
get_x_coordinate(const double phi) const {
    return (radius*cos(phi));
}

double
get_y_coordinate(const double phi) const {
    return (radius*sin(phi));
}

double
do_something(const double phi) const {
    auto const x = boost::math::differentiation::make_fvar<double, 2>(phi);
    auto fx = [this](auto x) { return get_x_coordinate(x); };
    auto fy = [this](auto x) { return get_y_coordinate(x); };
    auto const dx = fx(x);
    auto const dy = fy(x);
    return (dx.derivative(2)+dy.derivative(2));
}

由于以下错误,此示例失败。

无法将参数1从boost::math::differentiation::autodiff_v1::detail::fvar‘转换为“const”

我不能更改get_x_coordinate和get_y_coordinate接收一个const并返回一个double,因为我在我的代码中使用它们在其他位置。所以我真的不知道怎么继续下去。

另外,我正在使用2017。我问自己有什么区别

代码语言:javascript
复制
#include <boost/math/differentiation/autodiff.hpp>

代码语言:javascript
复制
#include <boost/math/differentiation/autodiff_cpp11.hpp>

如果我使用cpp11,是否必须使用VS2017?在我的boost版本中,两者都是可用的。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-03-17 21:33:41

感兴趣的函数将转换为可以接受double或boost fvar参数的模板。注意,boost提供了标准库(如sin,cos)中适合于fvar的三角函数的自定义实现。

代码语言:javascript
复制
#include <boost/math/differentiation/autodiff.hpp>
#include <iostream>
#include <math.h>

constexpr double const radius{4.0};

template <typename T>
T get_x_coordinate(T const & phi)
{
    return radius * cos(phi);
}

int main()
{
    double const phi{2.0};
    auto const x{::boost::math::differentiation::make_fvar<double, 2>(phi)};
    auto const dx{get_x_coordinate(x)};
    ::std::cout << dx.derivative(2) << ::std::endl;
    return 0;
}

联机编译器

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71423561

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档