Created
February 25, 2023 06:45
-
-
Save tenomoto/44ea642389bed7c19b6a80f29c8a27e1 to your computer and use it in GitHub Desktop.
serial quad in C
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
// C translation of https://www.nag-j.co.jp/fortran/coarray/code/quad1.f90 | |
#include <stdio.h> | |
#include <stdlib.h> | |
double rectangle_rule(double (*f)(double), double from, double to, int nstep) | |
{ | |
double integral; | |
double x1, x2, y, stepval; | |
int i; | |
if (to <= from) { | |
printf("Invalid from-to\n"); | |
exit(0); | |
}; | |
stepval = (to - from) / nstep; | |
x1 = from; | |
for (int i = 0; i < nstep; ++i) { | |
x2 = from + (i+1) * stepval; | |
y = f(0.5 * (x1 + x2)); | |
integral += y; | |
x1 = x2; | |
} | |
integral *= stepval; | |
return integral; | |
} |
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
double rectangle_rule(double (*f)(double), double, double, int); |
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
// C translation of https://www.nag-j.co.jp/fortran/coarray/code/serial.f90 | |
#include <time.h> | |
#include <stdio.h> | |
#include <math.h> | |
#include "quad1.h" | |
double f(double x) | |
{ | |
return 1.0 / (x * x); | |
} | |
int main(void) | |
{ | |
const double a = 1.0, b = 10.0; | |
const int steps = 1000000000; | |
double res, tres; | |
double secs; | |
clock_t t1, t2; | |
t1 = clock(); | |
res = rectangle_rule(f, a, b, steps); | |
t2 = clock(); | |
printf("Calculated value: %e\n", res); | |
tres = 1.0 - 0.1; | |
printf("True value (approx): %e\n", tres); | |
printf("Relative error): %e\n", fabs((res - tres)/tres)); | |
secs = (double)(t2 - t1) / (double)CLOCKS_PER_SEC; | |
printf("Time taken %e seconds\n", secs); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment