exp 11: init

Signed-off-by: Amneesh Singh <natto@weirdnatto.in>
This commit is contained in:
2022-12-27 15:22:58 +05:30
parent a7e89f1754
commit 077e1aa9bb
3 changed files with 64 additions and 59 deletions

View File

@@ -266,6 +266,7 @@ int main() {
#+end_src
#+LATEX: \clearpage
* Program for solving numerical integration by Simpson's 3/8 rule.
#+ATTR_LATEX: :options frame=single,breaklines=true
#+begin_src C :tangle 8.c :results output :exports both :wrap src text
@@ -297,65 +298,6 @@ int main() {
}
#+end_src
* Program for finding inverse of linear equations using Gauss Jordan method.
#+ATTR_LATEX: :options frame=single,breaklines=true
#+begin_src C :tangle 9.c :results output :exports both :wrap src text
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
double **inverse(double **matrix, int order) {
double **inverse = calloc(order, sizeof(double *));
for (int i = 0; i < order; i++) {
inverse[i] = calloc(2 * order, sizeof(double));
inverse[i][order + i] = 1;
memcpy(inverse[i], matrix[i], order * sizeof(double));
}
for (int i = 0; i < order; i++) {
for (int j = 0; j < order; j++) {
if (i == j)
continue;
double r = inverse[j][i] / inverse[i][i];
for (int k = 0; k < order * 2; k++)
inverse[j][k] -= r * inverse[i][k];
}
}
for (int i = 0; i < order; i++) {
for (int j = 0; j < order; j++)
inverse[i][j + order] /= inverse[i][i];
}
return inverse;
}
int main() {
const int ORDER = 3;
double **matrix = malloc(ORDER * sizeof(double *));
for (int i = 0; i < ORDER; i++)
matrix[i] = malloc(ORDER * sizeof(double));
matrix[0][0] = 92, matrix[0][1] = 4.5, matrix[0][2] = 61; // 92x + 4.5y + 61z = 0
matrix[1][0] = -2, matrix[1][1] = 0, matrix[1][2] = 92387; // -2x + 92387z = 0
matrix[2][0] = -2, matrix[2][1] = 0, matrix[2][2] = -23; // -2x - 23z = 0
double **inv = inverse(matrix, ORDER);
for (int i = 0; i < ORDER; i++) {
for (int j = 0; j < ORDER; j++)
printf("%lf ", inv[i][j + ORDER]);
printf("\n");
free(inv[i]);
free(matrix[i]);
}
free(inv);
free(matrix);
}
#+end_src
#+LATEX: \clearpage
* Program for finding inverse of linear equations using Gauss Jordan method.
@@ -483,3 +425,38 @@ int main() {
free(matrix);
}
#+end_src
#+LATEX: \clearpage
* Program for solving ordinary differential equation using Renge Kutta method.
#+ATTR_LATEX: :options frame=single,breaklines=true
#+begin_src C :tangle 11.c :results output :exports both :wrap src text
#include <stdio.h>
double f(double x, double y) { return (y * y - x) / (y + x * y * y); };
double rungen_kutta_4(double x0, double y0, double xn, int steps) {
double h = (xn - x0) / steps;
while (steps--) {
double k1 = f(x0, y0) * h;
double k2 = f(x0 + h / 2, y0 + k1 / 2) * h;
double k3 = f(x0 + h / 2, y0 + k2 / 2) * h;
double k4 = f(x0 + h, y0 + k3) * h;
double k = (k1 + k4 + 2 * (k2 + k3)) / 6;
x0 += h, y0 += k;
}
return y0;
}
int main() {
double x0 = 0, y0 = 5, xn = 1784;
int steps = 1000000;
printf("Value of y at x=%0.4lf is y=%0.4lf", xn,
rungen_kutta_4(x0, y0, xn, steps));
}
#+end_src