● 計算

テーブル演算

テーブル演算系関数は、FLOATEX 型の配列を計算します。演算はループ処理で代替できますが、テーブル演算関数を使用するとコードを簡潔にする事ができます。
関数は、リファレンスの「テーブル演算」を参照してください。

例.生産額と生産量の経年データに ax + b を当てはめ、生産量を推定する

#include "floatex.h"

/* 最小二乗法 */
void    coeff(
            FLOATEX_TBLPTR  x,
            FLOATEX_TBLPTR  y,
            int             n,
            PFLOATEX        a,
            PFLOATEX        b)
{
    FLOATEX     sx,sy,sxy,sxx,fn,d;
    FLOATEX     t1,t2;

    floatex_sum(x,n,sx);         /* Σx */
    floatex_sum(y,n,sy);         /* Σy */
    floatex_sum_mul(x,y,n,sxy);  /* Σxy */
    floatex_sum_square(x,n,sxx); /* Σx^2 */

    /* d = nΣx^2 - (Σx)^2 */
    floatex_longto(n,fn);
    floatex_esub(
        floatex_emul(fn,sxx,t1),
        floatex_emulx(sx,t2),
        d);

    /* a = (nΣxy - ΣxΣy) / d */
    floatex_esub(
        floatex_emul(fn,sxy,t1),
        floatex_emul(sx,sy,t2),
        a);
    floatex_div(a,d);

    /* b = (Σx^2Σy - ΣxyΣx) / d */
    floatex_esub(
        floatex_emul(sxx,sy,t1),
        floatex_emul(sxy,sx,t2),
        b);
    floatex_div(b,d);
}

#include <stdio.h>
#include <string.h>

#define MAX_CNT         30 /* 最大データ件数 */

/* 生産額、生産量の入力 */
int     input1(FLOATEX_TBLPTR x,FLOATEX_TBLPTR y)
{
    char    buf[32],*pstop;
    int     i;

    i = 0;
    do{
        do{
            printf("%2d : 生産額 = ",i+1);
            scanf("%s",buf);
            if (!strcmpi(buf,"end"))  /* end で終了 */
                return i;
        }while(floatex_ldstr_strtold(buf,&pstop,x[i]) || *pstop);

        do{
            printf("     生産量 = ");
            scanf("%s",buf);
            if (!strcmpi(buf,"end"))  /* end で終了 */
                return i;
        }while(floatex_ldstr_strtold(buf,&pstop,y[i]) || *pstop);

    }while(++i < MAX_CNT);

    return i;
}

/* 推定値の計算 */
void    input2(PFLOATEX a,PFLOATEX b)
{
    FLOATEX     x;
    char        buf[32],*pstop;

    while(1){
        do{
            printf("推定生産額 = ");
            scanf("%s",buf);
            if (!strcmpi(buf,"end"))  /* end で終了 */
                return;
        }while(floatex_ldstr_strtold(buf,&pstop,x) || *pstop);

        floatex_add(floatex_mul(x,a),b); /* x = ax + b */

        floatex_ldstr_ldtoa(x,buf);
        printf("推定生産量 : %s\n",buf);
    }
}

void    main(void)
{
    FLOATEX         x[MAX_CNT],y[MAX_CNT];
    FLOATEX         a,b;
    int             n;
    unsigned int    oldcw;
    char            buf[32];

    if (!floatex_ldstr_init()){
        printf("ldstr.dll が必要です\n");
        return;
    }

    oldcw = floatex_storecw();
    floatex_loadcw(FEX_PC_64 | FEX_RC_NEAR | FEX_MCW_EM);

    /* 生産額、生産量の入力 */
    if ((n = input1(x,y)) != 0){ /* 0 件の場合はプログラム終了 */

        coeff(x,y,n,a,b); /* a 、b を求める */

        /* 求めた a 、b を表示 */
        floatex_ldstr_ldtoa(a,buf);
        printf("a : %s  \n",buf);
        floatex_ldstr_ldtoa(b,buf);
        printf("b : %s  \n",buf);

        input2(a,b); /* 推定値の計算 */
    }

    floatex_ldstr_term();
    floatex_loadcw(oldcw);
}