Commit cebe0b55 authored by Taddeüs Kroes's avatar Taddeüs Kroes

Added 3 out of 4 integral functions to ass5.

parent 701929ef
typedef double (*func_ptr)(double x); typedef double (*func_ptr)(double);
#include <stdlib.h> #include <stdlib.h>
#include <stdio.h> #include <stdio.h>
#include <math.h> #include <math.h>
#include "func_ptr.h"
int main(void) { #define DX 1e-6
typedef double (*method_ptr)(func_ptr, double, double);
double rectangle(func_ptr f, double a, double b) {
return (b - a) * f((a + b) / 2);
}
double trapezoidal(func_ptr f, double a, double b) {
return 0.5 * (b - a) * (f(a) + f(b));
}
double simpson(func_ptr f, double a, double b) {
return (2 * rectangle(f, a, b) + trapezoidal(f, a, b)) / 3;
}
double integral(func_ptr f, method_ptr method, double a, double b) {
int steps = (int)((b - a) / DX), i;
double x, surface = 0;
for( i = 0; i < steps; i++)
surface += method(f, x = a + i * DX, x + DX);
return surface;
}
double f1(double x) {
return pow(M_E, -x);
}
double f2(double x) {
return x * pow(M_E, -x);
}
#define PRINT_INTEGRAL(func, method, a, b) (printf(#func " from " #a " to " \
#b " using " #method " method: %.11f\n", integral(&func, &method, a, b)))
int main(void) {
PRINT_INTEGRAL(f1, rectangle, 0, 1);
PRINT_INTEGRAL(f1, trapezoidal, 0, 1);
PRINT_INTEGRAL(f1, simpson, 0, 1);
return 0; return 0;
} }
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment