2014-01-14 3 views
0

나는 통합 작업을 수행하기위한 코드를 가지고 있으며, 67 번째 줄부터 시작하는 루프에 대해 임의로 생성 된 점에서 함수의 값을 누적하는 for 루프가 있습니다 (몬테카를로 통합). 불행하게도 루프가 끝나면 "monte2"변수의 결과로 NAN을 얻습니다. for 루프 안에 printf 문을 써서 실수를 찾아내어 235.494781 이후에 -nan으로 바뀌는 것을 알아 냈습니다. 이 문제의 원인은 무엇일까요? 우분투 12.04.3 LTS 32 비트를 실행하고 GCC 버전 4.6.3으로 일반 C 코드를 컴파일합니다. 당신의 도움에 감사드립니다. 코드는 다음과 같습니다 :누적 합계로서 나노 얻기

P.S :이 코드는 원래 Windows 8 64 비트 코드 블록에 제 친구가 작성했습니다.

#include<stdio.h> 
#include<math.h> 

float I1(float x) 
{ 
    return exp(-x)*cos(x*x)*cos(x*x); 
} 

float I2(float t) 
{ 
    return cos(log(t)*log(t))*cos(log(t)*log(t)); 
} 
float random() 
{ 
    float a; 
    a=rand()%1000; 
    a=a/1000*20; 
    // printf("%.15f\t%f\n",I1(a),a); 
    return a; 
} 
float random2() 
{ 
    float a; 
    a=rand()%1000; 
    a/=1000; 
    // printf("%.15f\t%f\n",I2(a),a); 
    return a; 
} 

int main() 
{ 
    FILE *data=fopen("data.txt","w"); 
    FILE *data2=fopen("data2.txt","w"); 

    float trap=0,monte=0,sum=0, monte2=0; 
    float a[1000],b[1000],dt=0.005; 
    int i; 

    /* Part 1 */ 

    for(i=0;i<1000;i++) 
    a[i]=I1(i*dt); 
    for(i=0;i<1000;i++) 
    fprintf(data,"%f\t%f\n",i*dt,a[i]); 

    for(i=1;i<1000;i++) 
    trap+=(a[i]+a[i-1])/2*dt; 
    printf("The integral value of I1 is = %f with trapezoid rule\n",trap); 


    for(i=0;i<500;i++) 
    monte+=I1(random()); 
    printf("The Monte Carlo Technique value for I1 is %f with 500 samples\n",monte/500*20); 

    /* Part 2 */ 
    dt=0.001; 
    printf(" \n"); 
    for(i=1;i<=1000;i++) 
    b[i]=I2(i*dt); 
    for(i=1;i<=1000;i++) 
    fprintf(data2,"%f\t%f\n",i*dt,b[i]); 

    for(i=2;i<=1000;i++) 
    trap+=(b[i]+b[i-1])/2*dt; 
    printf("The integral value of I2 is = %f with trapezoid rule\n",trap/2); 

    for(i=0;i<500;i++) 
    { 
    monte2+=I2(random2()); 
    printf("%f \n", monte2); 
    } 
    printf("The Monte Carlo Technique value of I2 is %f with 500 samples\n",monte2/500); 
    printf("\n"); 
    printf("Comment 1: Two values obtained with trapezoid rule is close to each other;however,they are not exactly same.\n"); 
    printf("\n"); 
    printf("Comment 2: The integral value and monte carlo value of I1 is closer than the integral value and monte carlo value of I2.This means that we have better expectation value of I1 with monte carlo technique with 500 samples.\n"); 
    fclose(data2); 
    fclose(data); 
    return 0; 
} 

답변

5

귀하의 함수 호출

monte2+=I2(random2()); 

NaN를 생성 할 수 있습니다. 이는 random20을 반환 할 수 있기 때문입니다. log 0은 무한대입니다. 이로 인해 cos(log(t)*log(t))*cos(log(t)*log(t))에서 NaN가 생성됩니다.

log 함수의 그래프를 참조하십시오 : 그래프가 y 축에 임의 가까이 가져 만 충족하거나 1 교차하지 않는

enter image description here

하는 것으로.


1. 소스 Wikipedia

+2

'로그 (0)'생성한다 -∞하지 NaN이 (IEEE 754 9.2.1 수학 의해 아니라 C 표준에 의해). NaN은'cos (log (t) * log (t))'에서 ∞의 코사인을 취하면 생성됩니다. –

+0

@EricPostpischil; 그래 네가 맞아. 나는'log 0'이'NaN'을 생성한다고 결코 말하지 않았습니다. 나는 함수 호출을 말했다. 그건 그렇고 그 점을 추가했습니다. – haccks

+0

이 점을 지적 해 주셔서 고맙습니다.이 점을 무시하고 나 자신을 부끄러워해야합니다. : S – Vesnog