-2

It is an optimization example of newton-raphson method. I get the error message when compiling :

a function-definition is not allowed here before '{' token

It points to the first line of the first function.

Any help? thank you in advance

#include <iostream>
#include <cmath>
#include <fstream>
#include <vector>
#include <numeric>
#include <iterator>
#include <map>
#include <string>

//C++ clang

using namespace std;

int main()
{
    //Optimization Example

    void getF( double* X, double *F)
    {
        F[0]=X[0]*X[0]+X[1]*X[1]-4;
        F[1]=-X[0]*X[0]/3+X[1];
        return;
    }

    void Jacobian(double* X, double** H)
    {
        H[0][0]=2*X[0];
        H[0][1]=2*X[1];
        H[1][0]=-2/3*X[0];
        H[1][1]=1;

        return;
    }

    unsigned int maxSteps=1000;
    double epsilon=0.00001;
    double* X=new double[2];
    double* F=new double[2];
    double** H= new double*[2];
    for (unsigned int i=0 ; i<2 ; i++)
    {
        H[i]=new double[2];
    }

    cout << "Solution : " << endl;
    cout << "x = " << X[0] << endl;
    cout << "y = " << X[1] << endl; 

    delete[] X;
    delete[] F;

    for (unsigned int i=0 ; i<2 ; i++)
    {
        delete[] H[i];
    }
    delete[] H;

}
Hassaan
  • 6,355
  • 5
  • 25
  • 44
JasBeck
  • 25
  • 5

2 Answers2

3

You cant have function inside the function in C++. The only workaround is to use lambdas from c++11:

int main() 
{
    auto my_fun= []() { return 69; };
    my_fun();
} 

Also try to avoid raw pointers. Its easy to make a mistake with them. Sticking to smart_pointer is a great way of providing reliable and safe memory allocation.

CyberGuy
  • 2,653
  • 1
  • 18
  • 29
-1

Here is the example from G.Seed's book,can be helpful for you.

first the header file for Newton-Raphson method

#ifndef _NR_H 
#define _NR_H
#include <cmath>
void NewtonRaphson(double (*f_ptr)(double),
                             double (*df_ptr)(double), int n_iterations,
                             double tolerance, double xO, double& x_new,
                             int& count, bool& converged);
#endif

Then function itself

#include "nr.h"
void NewtonRaphson(double (*f_ptr)(double), double (*df_ptr)(double),
                   int n_iterations, double tolerance, double xO, double& x_new,
                   int& count, bool& converged) {
    double x_old (xO);
    count = 0;
    converged = false;

    for (int i = O; i < n_iterations; i++) {
        count++;
        x_new = x_old - (f_ptr(x_old)/ df_ptr(x_old)) ;

        if (fabs(x_new - x_old) < tolerance) {
            converged = true;
            break;
        }
        else 
        x_old = x_new;
    }
}

Also you should put your one function in global scope as it was pointed out in ERic's comment.

Richard Rublev
  • 5,592
  • 9
  • 42
  • 87