TheAlgorithms-C-Plus-Plus/computer_oriented_statistical_methods/Secant_method.CPP

50 lines
633 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-12 02:33:09 +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-12 02:33:09 +08:00
}
void main()
{
2019-08-21 10:10:08 +08:00
float a, b, z, c, m, n;
2016-10-12 02:33:09 +08:00
clrscr();
2019-08-21 10:10:08 +08:00
for (int i = 0; i < 100; i++)
2016-10-12 02:33:09 +08:00
{
2019-08-21 10:10:08 +08:00
z = eq(i);
if (z >= 0)
2016-10-12 02:33:09 +08:00
{
2019-08-21 10:10:08 +08:00
b = i;
a = --i;
2016-10-12 02:33:09 +08:00
goto START;
}
}
2019-08-21 10:10:08 +08:00
START:
2016-10-12 02:33:09 +08:00
2019-08-21 10:10:08 +08:00
cout << "\nFirst initial: " << a;
cout << "\nSecond initial: " << b;
for (i = 0; i < 100; i++)
2016-10-12 02:33:09 +08:00
{
2019-08-21 10:10:08 +08:00
float h, d;
m = eq(a);
n = eq(b);
2016-10-12 02:33:09 +08:00
2019-08-21 10:10:08 +08:00
c = ((a * n) - (b * m)) / (n - m);
a = b;
b = c;
2016-10-12 02:33:09 +08:00
2019-08-21 10:10:08 +08:00
z = eq(c);
if (z > 0 && z < 0.09) // stoping criteria
2016-10-12 02:33:09 +08:00
{
goto END;
}
}
2019-08-21 10:10:08 +08:00
END:
cout << "\n\nRoot: " << c;
2016-10-12 02:33:09 +08:00
getch();
}