分配后长两次重置为0

时间:2015-11-12 00:53:37

标签: c++ c precision long-double

我一直在修补C / C ++中的一些疾病模型,并希望从中获得更多的精确度。我考虑使用长双精度,对于80位精度(我使用的是cygwin的GCC 4.8.3),但在用它计算之后,我得到一个“nan”(不是数字)输出值。这是我正在使用的代码。所有变量都是长双倍。

#include <cstdlib>
#include <iostream>
#include <cstdio>
#include <ctime>
#include <random>
#include <omp.h>
#include <cfloat>



using namespace std;

int
main ( int argc, char** argv )
{

    long double S, E, I, R, V, dS, dE, dI, dR, dV;
    long double a, b, g, t, c, d, e, f;
    long double dt = .005, tmax = 365;

    S = 318000000;
    I = 1;
    E = 0;
    R = 0;
    V = 0;

    FILE* F;

    F = fopen ( "valoresSIR1.txt", "w+" );
    //fprintf ( F, "Tempo, Susceptivel, Incubado, Infectado, Recuperado, Vacinado\n" );

    a = 0.000005; 
    b = 0.01;
    c = 0.05; 
    d = 0.000034; 
    e = 0.00000; 
    f = 0.0; 
    g = 0.000000;
    t = 0.0000;

    //printf("%Lg", a); exit(0);
    for ( long double i = 0; i < tmax; i += dt )
    {
        dS = ( - a * I * S - g + t * R + d * ( S + E + R + V ) - f * S ) * dt;
        dE = ( a * I * S - c * E - g ) * dt;
        dI = ( c * E - g - e * I - b * I ) * dt;
        dR = ( b * I - g - t * R ) * dt;
        dV = ( f * S - g ) * dt;


        S += dS;
        E += dE;
        I += dI;
        R += dR;
        V += dV;

        //printf ( "%Lg, %Lg, %Lg, %Lg, %Lg, %Lg\n", S, E, I, R, V );
        std::cout.precision (50);
        std::cout << S << std::endl;
        exit ( 0 );
        fprintf ( F, "%Lg, %Lg, %Lg, %Lg, %Lg, %Lg\n", i, S, E, I, R, V );
        switch ( ( int ) i )
        {
            case 0: std::cout << i << endl;
                break;
            case 100: std::cout << i << endl;
                break;
            case 200: std::cout << i << endl;
                break;
            case 300: std::cout << i << endl;
                break;
            case 4000: std::cout << i << endl;
                break;
            case 5000: std::cout << i << endl;
                break;
            case 6000: std::cout << i << endl;
                break;
            case 7000: std::cout << i << endl;
                break;

        }

    }

    fclose ( F );

    return 0;
}

预期输出值:http://pastebin.com/mJqkSVUf

1 个答案:

答案 0 :(得分:4)

计算dS = ( - a * I * S - g + t * R + d * ( S + E + R + V ) - f * S ) * dt;使用未初始化的变量V。这会导致未定义的行为。

当发生未定义的行为时,任何事情都可能发生。在您的情况下,它表现为nan是涉及V的操作的结果。