#include #include #include using namespace std; const double EPSILON = 1e-10; const int MAX_ITERATIONS = 100; double f(double x) { return x*x*x-5*x-1; } double fPrime(double x) { return 3*x*x-5; } // stolen from on line template int sgn(T val) { return (T(0) < val) - (val < T(0)); } void Bisection(double a, double b) { double mid, value; int count = 0; if (sgn(f(a)) == sgn(f(b))) { cout << "Error, bisection requires different signs " << endl; return ; } mid = (a+b)/2.0; value = f(mid); while (count < MAX_ITERATIONS and abs(value)> EPSILON) { cout << count <<"\t" << a << "\t" << b << "\t" << value << endl; if (sgn(f(a)) == sgn(value)) { a = mid; } else { b = mid; } count ++; mid = (a+b)/2.0; value = f(mid); } cout << count <<"\t" << a << "\t" << b << "\t" << value << endl; return; } void Newton(double a) { int count; while (abs(f(a)) > EPSILON and count < MAX_ITERATIONS) { cout << count << "\t" << a <<"\t" << f(a) << endl; count ++; a = a - f(a)/fPrime(a); } cout << count << "\t" << a <<"\t" << f(a) << endl; return; } void RegulaFalsi(double a, double b) { int count=0; double newPos,value; if (sgn(f(a)) == sgn(f(b))) { cout << "Error, regula falsi requires different signs " << endl; return ; } newPos = b-(f(b)*(b-a))/(f(b)-f(a)); value = f(newPos); while (abs(value) > EPSILON and count < MAX_ITERATIONS) { cout << count <<"\t" << a << "\t" << b << "\t" << value << endl; if (sgn(value) == sgn(f(a))) { a = newPos; } else { b = newPos; } count ++; newPos = b-(f(b)*(b-a))/(f(b)-f(a)); value = f(newPos); } cout << count <<"\t" << a << "\t" << b << "\t" << value << endl; return; } int main () { cout << fixed << setprecision(15); cout << "Bisection Method " << endl; Bisection(0,3); cout << endl << endl; cout << "Regula Falsi" << endl; RegulaFalsi(0,3); cout << endl << endl; cout << "Newton" << endl; Newton(3); }