can someone assist me with my newton raphson code

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • erry04
    New Member
    • Aug 2010
    • 2

    #1

    can someone assist me with my newton raphson code

    hi all,i just learn about newton raphson method and im thinking to create a code for it.(im not expert in c++,so my code could be wrong)
    For the function and it derivative,i hard code it in my program.
    im using:
    f(x)=-0.6x^2+2.4x+5.5
    f'(x)=-1.2x+2.4
    eps=0.00001
    initial guess=input by user

    the problem is something wrong with the answer.Can someone assist me???

    Code:
    #include<iostream>
    #include<cmath>
    using namespace std;
    double NRM(double x0,double eps);
    double f_one(double x);
    double f_one_prime(double x);
    double equation_1(double x0);
    double temp_criterion(double x0,double x_new);
    
    int main()
    {
    	double x0,root,eps=0.00001;
    
    	cout<<"enter the initial guess:";
    	cin>>x0;
    	if((f_one(x0)!=0) && (f_one_prime(x0)!=0))
    	{
    		root=NRM(x0,eps);
    	}
    	cout<<"Root is taken as:" << root<<endl;
    
    	getchar();
    	getchar();
    }
    double f_one(double x)
    {
    	return(-0.6*x*x+2.4*x+5.5);
    }
    double f_one_prime(double x)
    {
    	return(-1.2*x+2.4);
    }
    double NRM(double x0,double eps)
    {
    	double x_new,c_t,i=0;
    	x_new=0;
    	c_t=temp_criterion(x0,x_new);
    
    	do
    	{
    		x_new=equation_1(x0);
    		c_t=temp_criterion(x0,x_new);
    		cout<<"i="<<i++<<"|"<<"xi="<<x0<<"|"<<"temp criterion="<<c_t<<endl;
    		x0=x_new;
    	}while(c_t>eps);
    	return(x_new);
    }
    double temp_criterion(double x0,double x_new)
    {
    	return((abs(x_new-x0))/abs(x_new));
    }
    double equation_1(double x0)
    {
    	double term;
    
    	term=f_one(x0)/f_one_prime(x0);
    	return(x0-term);
    	
    }
  • newb16
    Contributor
    • Jul 2008
    • 687

    #2
    f(x)=-0.6x^3+2.4x^2+5 .5
    f'(x)=-1.2x^2+2.4

    Derivative is wrong and doesn't match what is in the code. Then, if initial guess is right or derivative is 0, you print garbage that sits in root and not what's required.

    Comment

    • erry04
      New Member
      • Aug 2010
      • 2

      #3
      oh,i mistype my function,it should be
      f(x)=-0.6x^2+2.4x+5.5
      f'(x)=-1.2x+2.4

      Comment

      • newb16
        Contributor
        • Jul 2008
        • 687

        #4
        For initial guesses 0 and 2.2 it finds -1.628 and 5.628 as roots that seems to be right.
        So if you feel that "something wrong with the answer." and no more details, then you only have to "change something in the code".

        Comment

        Working...