Newton's method in c++

  • Comp Sci
  • Thread starter Sumaya
  • Start date
  • #1
Sumaya
29
0

Homework Statement



why the loop not looping ?

Homework Equations



fun1=x^3+4^2-x-1
fun2=3x^2+8x-1

The Attempt at a Solution



Code:
#include "stdafx.h"
#include<iostream>
using namespace std;
float fun1(float);
float fun2(float);
void main()
{
float a;
cin>>a;

if (fun2(a)>0)

do
{
	a=a-(fun1(a)/fun2(a));
	cout<<a<<endl;

	
}
	while(fun2(a)<0.001);
	


}
		 
float fun1( float a)
{
	float y;
	y=a*a*a+4*a*a-a-1;
	return y;
}
float fun2( float b)
{
	float y;
	y=3*b*b+8*b-1;
	return y;
}
 

Answers and Replies

  • #2
Borek
Mentor
29,168
3,844
Try to trace your program watching values of variable a and values returned by fun1 and fun2. Is it doing what you hoped for, or is it doing something else?
 
  • #3
vivekrai
72
0
Code:
while(fun2(a)<0.001);

Are you sure about this?
 
  • #4
GingerLee
20
0
Keep two variables for iterations.
If the difference between them is < 0.001 then stop loop.

Something like this :

x1 = a - (fun1(a) / fun2(a));

do{
x0 = x1;
x1 = x0 - (fun1(x0) / fun2(x0));
d = x0 - x1;
}while(d > 0.001);
 
  • #5
TheoMcCloskey
185
3
Also, check your (math in) function FUN2.
 
  • #7
TheoMcCloskey
185
3
I don't see anything wrong with it.

You're CORRECT - I misread OP's function F(x)! fun2 code is correct for fun1 code.
 
  • #8
36,696
8,687
You're CORRECT - I misread OP's function F(x)! fun2 code is correct for fun1 code.
?

Maybe you're referring to this line in the OP, in the Relevant equations section:
sumaya said:
fun1=x^3+4^2-x-1
There's a missing x. 4^2 should be 4*x^2.
The code has the right formula, though.
 
  • #9
Sumaya
29
0
thank u all
 

Suggested for: Newton's method in c++

  • Last Post
Replies
2
Views
626
Replies
2
Views
218
  • Last Post
Replies
9
Views
772
  • Last Post
Replies
12
Views
523
Replies
2
Views
313
Replies
1
Views
285
Replies
2
Views
245
Replies
15
Views
611
  • Last Post
Replies
7
Views
432
  • Last Post
Replies
1
Views
905
Top