TheAlgorithms-C-Plus-Plus/Computer Oriented Statistical Methods/Newton_Raphson.CPP

54 lines
697 B
C++
Raw Normal View History

2019-08-21 10:10:08 +08:00
#include <iostream.h>
#include <conio.h>
#include <math.h>
2016-10-09 14:18:51 +08:00
float eq(float i)
{
2019-08-21 10:10:08 +08:00
return (pow(i, 3) - (4 * i) - 9); // original equation
2016-10-09 14:18:51 +08:00
}
float eq_der(float i)
{
2019-08-21 10:10:08 +08:00
return ((3 * pow(i, 2)) - 4); // derivative of equation
2016-10-09 14:18:51 +08:00
}
void main()
{
2019-08-21 10:10:08 +08:00
float a, b, z, c, m, n;
2016-10-09 14:18:51 +08:00
clrscr();
2019-08-21 10:10:08 +08:00
for (int i = 0; i < 100; i++)
2016-10-09 14:18:51 +08:00
{
2019-08-21 10:10:08 +08:00
z = eq(i);
if (z >= 0)
2016-10-09 14:18:51 +08:00
{
2019-08-21 10:10:08 +08:00
b = i;
a = --i;
2016-10-09 14:18:51 +08:00
goto START;
}
}
2019-08-21 10:10:08 +08:00
START:
2016-10-09 14:18:51 +08:00
2019-08-21 10:10:08 +08:00
cout << "\nFirst initial: " << a;
cout << "\nSecond initial: " << b;
c = (a + b) / 2;
2016-10-09 14:18:51 +08:00
2019-08-21 10:10:08 +08:00
for (i = 0; i < 100; i++)
2016-10-09 14:18:51 +08:00
{
float h;
2019-08-21 10:10:08 +08:00
m = eq(c);
n = eq_der(c);
2016-10-09 14:18:51 +08:00
2019-08-21 10:10:08 +08:00
z = c - (m / n);
c = z;
2016-10-09 14:18:51 +08:00
2019-08-21 10:10:08 +08:00
if (m > 0 && m < 0.009) // stoping criteria
2016-10-09 14:18:51 +08:00
{
goto END;
}
}
2019-08-21 10:10:08 +08:00
END:
cout << "\n\nRoot: " << z;
2016-10-09 14:18:51 +08:00
getch();
}