Newtone Algorithm problem

Hello everyone!
I'm getting -nan(ind) as a result i have tried this code with other functions and it worked pretty well as a result i should get something like a=0.44357 with 5-6 iteractions.Sorry for language in cout's but it's for my labs in comments i added "translation" :p as imput i use eps=0.000000000001 starting point =0 number of iteraction 100

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
  
#define _USE_MATH_DEFINES
#include <iostream>
#include <iomanip>
#include <math.h>

using namespace std;


const double eps1 = 0.0000000001;

const double eps2 = 0.0000000001;


double funkcja(double x)
{
	return (pow(M_E, -x)) - sin((M_PI / 2)*x);
}


double pochodna(double x)
{
	return pow(-M_E, -x) - (M_PI/2)*cos((M_PI *x) / 2);
}

int main()

{

	double a, x1, f0, f1;
	int n;
	cout << "Podaj punkt startowy: ";// starting point

	cin >> a;
	cout << "Podaj liczbe iteracji: ";//number of iteractions
	cin >> n;

	x1 = a - 1;
	f0 = funkcja(a);
	while(n && (fabs(x1 - a) > eps2) && (fabs(f0) > eps1))
	{
		f1 = pochodna(a);
		if (fabs(f1) < eps1)
		{
		        cout << "Bledny punkt startowy";//wrong startingpoint
			n = 0;
			break;
		}
		x1 = a;
		a = a - f0 / f1;
		f0 = funkcja(a);
		if (!(--n))
		cout << "Nie znaleziono miejsc zerowych";//roots not found
	}
	cout << "a = " << setw(8) << a << endl;
	system("pause");
	return 0;
}
Last edited on
in pochodna(): pow(-M_E, -x)
read carefully.
you are doing (-e)^(-x) when you should be doing -(e^(-x))

also, consider using http://www.cplusplus.com/reference/cmath/exp/
Last edited on
Thanks a lot !
Works well
Topic archived. No new replies allowed.