Created
June 18, 2017 15:27
-
-
Save anonymous/338674f54a7011fd7edd25927030f519 to your computer and use it in GitHub Desktop.
Numerical Method
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <math.h> | |
double f (double x) | |
{ | |
return x*x*x - 2 *x + 2; | |
} | |
double df(double x) | |
{ | |
return 3*x*x - 2; | |
} | |
double bisection(double a, double b) | |
{ | |
double fa = f(a); | |
double fb = f(b); | |
double m; | |
if (fa * fb > 0) | |
{ | |
printf("Invalid starting point.\n"); | |
return 0.0; | |
} | |
int count = 0, MaxCount = 50; | |
while (count++ < 50) | |
{ | |
m = (a + b)/2.0; | |
double fm = f(m); | |
if (fabs(fm) < 1e-7) | |
{ | |
return m; | |
} | |
if (fa * fm < 0) | |
{ | |
b = m; | |
fb = fm; | |
} | |
else | |
{ | |
a = m; | |
fa = fm; | |
} | |
printf("%lf \t %lf\n", m, fm); | |
} | |
return m; | |
} | |
double newton(double x) | |
{ | |
double fx = f(x); | |
double dfx = df(x); | |
double nx = x; | |
do | |
{ | |
x = nx; | |
fx = f(x); | |
dfx = df(x); | |
printf("%lf \t %lf \n", x, fx); | |
nx = x - fx/dfx; | |
} | |
while (fabs(nx-x) > 1e-7); | |
return x; | |
} | |
int main() | |
{ | |
printf("Hello, World!\n"); | |
double a, b; | |
scanf("%lf %lf", &a, &b); | |
double p = bisection(a, b); | |
printf("Soultion: %lf\n", p); | |
scanf("%lf", &a); | |
double q = newton(a); | |
printf("Solution :%lf\n", q); | |
return 0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment