Find answers, ask questions, and connect with our <br>community around the world.

Home Forums CPP scientific computing discussion Mini project assignment-newton raphson method

• # Mini project assignment-newton raphson method

Posted by on March 29, 2024 at 7:16 pm

code:

#include<iostream>

#include<cmath>

#include<cassert>

//this program is on newton raphson method//

int main(int argc, char *argv[])

{

float dx,y,y1, fx,fx1,fdiff,fdiff1;

for(float i=1.00;i<101.00;i++)

{

fx=exp(i)+(i*i*i)-5;fx1=exp(i-1)+((i-1)*(i-1)*(i-1)-5);

fdiff=exp(i)+(3*i*i);fdiff1=exp(i-1)+(3*(i-1)*(i-1));

y=i-(fx/fdiff);y1=(i-1)-(fx1/fdiff1);

dx=abs(y1-y);

std::cout<<“y at “<<i-1<<” is “<<y1<<” y at “<< i<<” is “<<y<<std::endl;

if(dx< 1*exp(-5))

{

std::cout<<“Final iterated value is at “<<i<<” th iteration .i.e “<<y<<std::endl; break;

}

}

return 0;

}

Result:

l@DESKTOP-53SFBVP:~/workspace\$ g++ nr.cpp

l@DESKTOP-53SFBVP:~/workspace\$ ./a.out

y at 0 is 4 y at 1 is 1.22414

y at 1 is 1.22414 y at 2 is 1.46418

Final iterated value is at 2 th iteration .i.e 1.46418

Issue: code is ending before it reaches the tolerance 10^(-5)

what’s the issue in this code! thanks in advancee

replied 2 weeks, 5 days ago 2 Members · 1 Reply
• ### Rahul

Member
April 1, 2024 at 7:18 am

Hi Prem,

I would suggest you compare the values obtained from the code using theoretical calculations since this is a simple problem. This should help you to confirm if the equations are correct.

Also, I see you have used 1*exp(-5) in the if condition while checking for convergence. The exp() function in C++ gives the value of e raised to the exponent. In this case, the condition can be interpreted to be 2.718*10e-5. This is not correct. You can use either the pow() function of simply the ^ operator for this.

Best regards
Rahul