错误:表达式不能用作函数

error: expression cannot be used as a function

本文关键字:函数 不能 表达式 错误      更新时间:2023-10-16

有my.hpp :

#include <utility>
#ifndef ROBBINS_MONRO
#define ROBBINS_MONRO

template <class Func, class DetermSeq, class RandomV, class RNG>
std::pair<double,double> robbins_monro(const Func & h, double x_init, double alpha, const DetermSeq & epsilon, RandomV & U, RNG & G, long unsigned N){
for(int i=0; i<N; i++){
x_init-= epsilon(i+1)(h(x_init) - alpha + U(G));
}
return std::make_pair(x_init, h(x_init));
}

#endif

我的测试1a.cpp:

#include <cmath>
#include <ctime>
#include <random>
#include "robbinsmonro.hpp"
#include <iostream>

int main() {
auto h = [](double x) { return 1/(1+exp(-x)); };
double alpha = 2/3;
std::uniform_real_distribution<double> U(-0.1,0.1);
double x_init=0;
auto epsilon = [] (long unsigned n) { return 1/(1+n); };
std::mt19937 G(time(NULL));
std::pair<double,double> a,b;
a = robbins_monro(h, x_init, alpha, epsilon,  U, G, 1000000);
b = robbins_monro(h, x_init, alpha, epsilon,  U, G, 10000000);
std::cout << "Pour N= 1000000, on obtient x= " << std::get<0>(a) << " (et h(x)= " << std::get<1>(b) << ")" << std::endl;
std::cout << "Pour N= 10000000, on obtient x= " << std::get<0>(b) << " (et h(x)= " << std::get<1>(b) << ")" << std::endl;
return 0;
}

我有这个错误:

错误:表达式不能用作函数

对于行:

x_init-= ε(i+1((h(x_init( - alpha + U(G((;

我不明白,因为所有术语都是双重的,而不是"函数">

我假设你想在这里做一个乘法,为此你需要*运算符:

x_init -= epsilon(i+1) * (h(x_init) - alpha + U(G));
//  ^^^

您编写的表达式在通常的代数中有意义,但在 c++ 中,第二个括号成为对epsilon(i+1)结果的函数调用。由于这返回了一个unsigned long long,它不是一个函数,你不能调用它。

此外,在此 lambda 中:

[] (long unsigned n) { return 1/(1+n); };

除非n0,否则这个函数将永远返回0,因为你正在做整数除法。相反,您可以执行以下操作:

[] (long unsigned n) { return 1. /(1+n); };