-
Notifications
You must be signed in to change notification settings - Fork 0
/
numerical.c
91 lines (85 loc) · 1.48 KB
/
numerical.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#include <math.h>
#include <stdlib.h>
int interpol(const double *x,
const double *fx,
unsigned int n,
const double *z,
double *pz,
unsigned int m){
int j;
double *table = NULL;
double *coeff = NULL;
if((table = (double *)malloc(sizeof(double)*n)) == NULL){
return -1;
}
if((coeff = (double *)malloc(sizeof(double)*n)) == NULL){
free(table);
return -1;
}
memcpy(table, fx, sizeof(double)*n);
coeff[0] = table[0];
for(int r=1; r<n; r++){
for(int i=0; i<n-r; i++){
j = i + r;
table[i] = (table[i+1] - table[i])/(x[j]-x[i]);
}
coeff[r] = table[0];
}
free(table);
while(m--){
pz[m] = coeff[0];
for(int p=1; p<n; p++){
double temp = coeff[p];
for(int q=0; q<p; q++){
temp *= (z[m]-x[q]);
}
pz[m] += temp;
}
}
free(coeff);
return 0;
}
void lesq(const double *x,
const double *y,
unsigned int n,
double *k,
double *b){
double sum[4] = {0.0, };
for(int i=0; i<n; i++){
sum[0] += x[i]*y[i];
sum[1] += x[i];
sum[2] += y[i];
sum[3] += x[i]*x[i];
}
*k = (n*sum[0]-sum[1]*sum[2])/(n*sum[3]-sum[1]*sum[1]);
*b = (sum[2]-(*k)*sum[1])/n;
}
int getroot(double (*f)(double x),
double (*g)(double x),
double *x,
int *n,
double delta){
int satisfied, i;
i = 0;
satisfied = 0;
while(!satisfied && i+1<*n){
x[i+1] = x[i] - f(x[i])/g(x[i]);
if(fabs(x[i+1]-x[i]) < delta){
satisfied = 1;
break;
}
i++;
}
if(i == 0){
*n = 1;
}
else{
*n = i + 1;
}
if(satisfied){
return 0;
}
else{
return -1;
}
}