Graphviz 13.0.0~dev.20250210.0415
Loading...
Searching...
No Matches
solve.c
Go to the documentation of this file.
1/*************************************************************************
2 * Copyright (c) 2011 AT&T Intellectual Property
3 * All rights reserved. This program and the accompanying materials
4 * are made available under the terms of the Eclipse Public License v1.0
5 * which accompanies this distribution, and is available at
6 * https://www.eclipse.org/legal/epl-v10.html
7 *
8 * Contributors: Details at https://graphviz.org
9 *************************************************************************/
10
11/* solves the system ab=c using gauss reduction */
12#include <assert.h>
13#include <common/render.h>
14#include <math.h>
15#include <neatogen/neatoprocs.h>
16#include <stdio.h>
17#include <stdlib.h>
18#include <util/alloc.h>
19#include <util/gv_math.h>
20
21void solve(double *a, double *b, double *c, size_t n) { // a[n][n],b[n],c[n]
22
23 assert(n >= 2);
24
25 const size_t nsq = n * n;
26 double *asave = gv_calloc(nsq, sizeof(double));
27 double *csave = gv_calloc(n, sizeof(double));
28
29 for (size_t i = 0; i < n; i++)
30 csave[i] = c[i];
31 for (size_t i = 0; i < nsq; i++)
32 asave[i] = a[i];
33 /* eliminate ith unknown */
34 const size_t nm = n - 1;
35 for (size_t i = 0; i < nm; i++) {
36 /* find largest pivot */
37 double amax = 0.;
38 size_t istar = 0;
39 for (size_t ii = i; ii < n; ii++) {
40 const double dum = fabs(a[ii * n + i]);
41 if (dum < amax)
42 continue;
43 istar = ii;
44 amax = dum;
45 }
46 /* return if pivot is too small */
47 if (amax < 1.e-10)
48 goto bad;
49 /* switch rows */
50 for (size_t j = i; j < n; j++) {
51 const size_t t = istar * n + j;
52 SWAP(&a[t], &a[i * n + j]);
53 }
54 SWAP(&c[istar], &c[i]);
55 /*pivot */
56 const size_t ip = i + 1;
57 for (size_t ii = ip; ii < n; ii++) {
58 const double pivot = a[ii * n + i] / a[i * n + i];
59 c[ii] -= pivot * c[i];
60 for (size_t j = 0; j < n; j++)
61 a[ii * n + j] = a[ii * n + j] - pivot * a[i * n + j];
62 }
63 }
64 /* return if last pivot is too small */
65 if (fabs(a[n * n - 1]) < 1.e-10)
66 goto bad;
67 b[n - 1] = c[n - 1] / a[n * n - 1];
68 /* back substitute */
69 for (size_t k = 0; k < nm; k++) {
70 const size_t m = n - k - 2;
71 b[m] = c[m];
72 const size_t mp = m + 1;
73 for (size_t j = mp; j < n; j++)
74 b[m] -= a[m * n + j] * b[j];
75 b[m] /= a[m * n + m];
76 }
77 /* restore original a,c */
78 for (size_t i = 0; i < n; i++)
79 c[i] = csave[i];
80 for (size_t i = 0; i < nsq; i++)
81 a[i] = asave[i];
82 free(asave);
83 free(csave);
84 return;
85bad:
86 printf("ill-conditioned\n");
87 free(asave);
88 free(csave);
89 return;
90}
Memory allocation wrappers that exit on failure.
static void * gv_calloc(size_t nmemb, size_t size)
Definition alloc.h:26
void free(void *)
Arithmetic helper functions.
#define SWAP(a, b)
Definition gv_math.h:130
void solve(double *a, double *b, double *c, size_t n)
Definition solve.c:21