# Demo entry 2241764

Gram Schmidt

Submitted by anonymous on Jul 17, 2015 at 13:35
Language: C. Code size: 2.2 kB.

```#include <stdio.h>
#include <math.h>
typedef struct Vector {
int dim;
double seibun[100];
} Vector;

Vector VecNormalize(Vector u);
Vector VecProj(Vector u,Vector v);
Vector VecSub(Vector u, Vector v);
Vector VecScale(double m, Vector u);
double VecDot(Vector u, Vector v);
double VecNorm(Vector u);
int VecShow(Vector u);

int main() {
int i,j;
Vector v[3] = {
{3, {1.0, 0.0, -1.0}},
{3, {2.0, 1.0, 0.0}},
{3, {1.0, 2.0, 2.0}},
};
puts("与えられたベクトル組");
for (i=0; i<3; i++)
VecShow(v[i]);
// グラムシュミット正規直交化
Vector u, e[3];
for (i=0; i<3; i++) {
u = v[i];
for (j=0; j<i; j++)
u = VecSub(u, VecProj(v[i],e[j]));
e[i] = VecNormalize(u);
}
puts("正規直交化結果");
for (i=0; i<3; i++)
VecShow(e[i]);
return 0;
}

Vector VecProj(Vector u,Vector v) {
double dotuv = VecDot(u,v);
double dotvv = VecDot(v,v);
Vector proj  = VecScale(dotuv/dotvv, v);
return proj;
}

Vector VecAdd(Vector u, Vector v) {
Vector tmp;
tmp.dim=u.dim;
int i;
for (i=0; i<tmp.dim; i++)
tmp.seibun[i] = u.seibun[i] + v.seibun[i];
return tmp;
}

Vector VecSub(Vector u, Vector v) {
Vector tmp;
tmp.dim=u.dim;
int i;
for (i=0; i<tmp.dim; i++)
tmp.seibun[i] = u.seibun[i] - v.seibun[i];
return tmp;
}

Vector VecScale(double m, Vector u) {
Vector tmp;
tmp.dim=u.dim;
int i;
for (i=0; i<tmp.dim; i++)
tmp.seibun[i] = m*u.seibun[i];
return tmp;
}

double VecDot(Vector u, Vector v) {
int i;
double tmp=0.0;
for (i=0; i<u.dim; i++)
tmp += u.seibun[i] * v.seibun[i];
return tmp;
}

double VecNorm(Vector u) {
return sqrt(VecDot(u,u));
}

Vector VecNormalize(Vector u) {
Vector zero = {3,{0.0}};
double norm_u = VecNorm(u);
if (norm_u < 1e-13)
return zero;
else
return VecScale(1/norm_u, u);
}

int VecShow(Vector u) {
int i;
printf("[");
for (i=0; i<u.dim; i++)
printf("%6.3f ",u.seibun[i]);
printf(" ]\n");
return 0;
}
```

This snippet took 0.01 seconds to highlight.

Back to the Entry List or Home.