Skip to content

Instantly share code, notes, and snippets.

@bugaevc
Last active August 29, 2015 14:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bugaevc/a5690d04ce44b65b16f8 to your computer and use it in GitHub Desktop.
Save bugaevc/a5690d04ce44b65b16f8 to your computer and use it in GitHub Desktop.
Homework task
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define F(x) (f(x)-g(x))
#define F1(x) (f1(x)-g1(x))
typedef double (*func)(double);
double root(func f, func g, func f1, func g1, double a, double b, double eps1)
{
int right = F1(a) * (F1(b)-F1(a)) > 0;
if(right)
eps1 = -eps1;
double c = right ? a : b;
while(F(c)*F(c+eps1) > 0)
c = c - F(c)/F1(c);
return c;
}
double integral(func f, func g, double a, double b, double eps2)
{
int N = 1;
double oldI, I = -1.0;
do
{
oldI = I;
I = F(a) + F(b);
double h = (b-a) / N;
int i;
for(i = 1; i < N; i++)
if(i % 2)
I += 2 * F(a+i*h);
else
I += 4 * F(a+i*h);
I *= h/3;
N *= 2;
}
while((N == 1) || (fabs(oldI - I) >= eps2 * 15));
return I;
}
double ff(double x)
{
return 0.35*x*x - 0.95*x + 2.7;
}
double ff1(double x)
{
return 0.35*2*x - 0.95;
}
double gg(double x)
{
return pow(3, x) + 1;
}
double gg1(double x)
{
return log(3) * pow(3, x);
}
double hh(double x)
{
return 1/(x+2);
}
double hh1(double x)
{
return -1/(x+2)/(x+2);
}
int main()
{
double
x1 = root(hh, ff, hh1, ff1, -1.95, -1.5, 0.000001), // about -1.8
x2 = root(gg, hh, gg1, hh1, -1.75, -1.0, 0.000001), // about -1.2
x3 = root(ff, gg, ff1, gg1, -2.00, 1.00, 0.000001); // about 0.32
printf("%f %f %f\n", x1, x2, x3);
double res =
integral(ff, hh, x1, x2, 0.000001) +
integral(ff, gg, x2, x3, 0.000001); // about 3.94
printf("%f\n", res);
return 0;
}
@bugaevc
Copy link
Author

bugaevc commented Feb 15, 2015

Results:
-1.821137 -1.209384 0.324613
3.948069

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment