Нахождение корней методом Ньютона

Рейтинг: 1Ответов: 1Опубликовано: 03.12.2014

Помогите, пожалуйста, с одной проблемой. Я никак не могу вывести значение х.

#include <iostream>
#include <math.h>

using namespace std;

#define JMAX 20 //Set to maximum number of iterations.
double rtnewt(void (*funcd)(double, double *, double *), double x1, double x2, double   xacc)
/*Using the Newton-Raphson method, find the root of a function known to lie in the  interval
[x1, x2]. The root rtnewt will be refined until its accuracy is known within ±xacc. funcd
is a user-supplied routine that returns both the function value and the first derivative of the
function at the point x.*/
{
    int j;
double df,dx,f,rtn;
rtn=0.5*(x1+x2); //Initial guess.
for (j=1;j<=JMAX;j++) {
    (*funcd)(rtn,&f,&df);
    dx=f/df;
    rtn -= dx;
    if ((x1-rtn)*(rtn-x2) < 0.0) {
        /*printf("Jumped out of brackets in rtnewt\n");*/
    }
    if (fabs(dx) < xacc) {
        return rtn; //Convergence.
    }
}
printf("Maximum number of iterations exceeded in rtnewt\n");    
return 0.0; //Never get here.
}

void myf(double x, double* f, double* df) 
{
*f = exp(-pow(x,2))-0.01;
*df = -2*x*exp(-pow(x,2));  
//cout<<x<<endl;
}

int main()
{
/*printf("%.10f", rtnewt(myf, -3.0f, -2.0f, 0.0001f),"\n");*/
cout<<"f("<<"***"<<")="<<rtnewt(myf, -3.0f, -2.0f, 0.0001f)<<endl;      
system("pause");
return 0;
}

Ответы

▲ 1
  1. if (fabs(dx) < xacc) почему Вы сравниваете с точностью вычисления приращение аргумента. Сравнивайте значение самой функции.
  2. pow(x,2) это нехорошо. Просто Х * Х
  3. У Вас что, упражнение на указатели на функции? Зачем эти ужасы?