Demo entry 2269968

CGS2

   

Submitted by anonymous on Jul 19, 2015 at 15:10
Language: C. Code size: 2.5 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 VecAdd(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,vecDim,vecNum;
    Vector v[100];
    puts("ベクトルの個数を入力してください。");
    scanf("%d",&vecNum);
    puts("ベクトルの次元を入力してください。");
    scanf("%d",&vecDim);
    for(j=0; j<vecNum; j++) {
        v[j].dim=vecDim;
        printf("%d 番目のベクトルの各成分を入力してください。\n", j);
        for(i=0; i<vecDim; i++) {
            scanf("%lf", &v[j].seibun[i]);
        }
    }

    puts("与えられたベクトル組");
    for (j=0; j<vecNum; j++)
        VecShow(v[j]);
    // グラムシュミット正規直交化
    Vector u, e[100];
    for (j=0; j<vecNum; j++) {
        u = v[j];
        for (i=0; i<j; i++)
            u = VecSub(u, VecProj(v[j],e[i]));
        e[j] = VecNormalize(u);
    }
    puts("正規直交化結果");
    for (j=0; j<vecNum; j++)
        VecShow(e[j]);
    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.

Delete this entry (admin only).