diff --git a/cpp/bisection.cpp b/cpp/bisection.cpp new file mode 100644 index 0000000..78f1614 --- /dev/null +++ b/cpp/bisection.cpp @@ -0,0 +1,58 @@ +#include +using namespace std; + +#define EPSILON 0.01 +#define MOD 1000 + +int MAX_POWER; +double coef_arr[MAX_POWER+1]; + +double get_val(double x){ + double val = 0; + for(int i=0; i<=MAX_POWER; i++){ + val += coef_arr[i]*pow(x, i); + } + return val; +} + +double get_roots_by_bisection(double a, double b){ + double c; + if(get_val(b)<0){ + c=b; + b=a; + a=c; + } + while (abs(b-a) >= EPSILON){ + c = (a+b)/2; + + if (get_val(c) == 0.0) + break; + + else if (get_val(c)*get_val(a) < 0) + b = c; + + else + a = c; + } + return c; +} + +int main(){ + srand(time(0)); + double a, b, ans; + + cout << "Enter highest power in polynomial"; + cin >> MAX_POWER; + + cout << "Enter co-effecients of polynomial starting from degree 0 to " << MAX_POWER; + for(int i=0; i<=MAX_POWER; i++){ + cin >> coef_arr[i]; + } + + a = -rand()%MOD; + b = rand()%MOD; + ans = get_roots_by_bisection(a, b); + + cout << " The value of root is : " << ans; + return 0; +} diff --git a/cpp/newton_rhapson.cpp b/cpp/newton_rhapson.cpp new file mode 100644 index 0000000..15d543f --- /dev/null +++ b/cpp/newton_rhapson.cpp @@ -0,0 +1,41 @@ +//Newton-Raphson Method +#include +#include +#include +using namespace std; +double f(double x); //declare the function for the given equation +double f(double x) //define the function here, ie give the equation +{ + double a=pow(x,3.0)-x-11.0; //write the equation whose roots are to be determined + return a; +} +double fprime(double x); +double fprime(double x) +{ + double b=3*pow(x,2.0)-1.0; //write the first derivative of the equation + return b; +} +int main() +{ + double x,x1,e,fx,fx1; + cout.precision(4); //set the precision + cout.setf(ios::fixed); + cout<<"Enter the initial guess\n"; //take an intial guess + cin>>x1; + cout<<"Enter desired accuracy\n"; //take the desired accuracy + cin>>e; + fx=f(x); + fx1=fprime(x); + cout <<"x{i}"<<" "<<"x{i+1}"<<" "<<"|x{i+1}-x{i}|"<=e); /*if |x{i+1}-x{i}| remains greater than the desired accuracy, continue the loop*/ + cout<<"The root of the equation is "<