c: investigate float

來源:互聯網
上載者:User
#include <stdio.h>
#include <math.h>
#include <assert.h>

double f(int x)
{
    return 1.0/x;
}

void Test1()
{
    double a,b;
    int i;
    a=f(10);
    b=f(10);
    i = a==b;
    printf("%d\n", i);
}

void Test2()
{
    double a,b,c;
    int i;
    a=f(10);
    b=f(10);
    c=f(10);
    i = a==b;
    printf("%d\n", i);
}

template <typename T>
void PrintBin(T const &t)
{
    int n = sizeof(t)*8;
    for(int i=n-1; i>=0; i--)
    {
        printf("%d", (t>>i)&1);
        if(i%4==0) printf(" ");
    }
    printf("\n");
}

void Test3()
{
    float a = -625512485.15542145;
    //unsigned char *u = (unsigned char *)&a;
    //printf("%x %x %x %x\n", u[0], u[1], u[2], u[3]);
    printf("%.15g \n", a);
    
    unsigned int *n = (unsigned int *)&a;    //For double, MUST use  long long
    printf("%x \n", *n);
    PrintBin(*n);
    //PrintBin(a);
    
    int e = 8;
    int m = 23;
    
    if(sizeof(a)==sizeof(float))
    {
        e = 8;
        m = 23;
    }
    else
    {
        assert(sizeof(a)==sizeof(double));
        e = 11;
        m = 52;
    }
    assert(1+e+m==sizeof(a)*8);;
    
    int S = (*n) >> (e+m);
    int Ep = ((*n) << 1) >> (m+1);
    int Mp = ((*n)<<(1+e))>>(1+e);
//    printf("S %x Ep %x Mp %x \n", S, Ep, Mp);
    printf("S  ");
    PrintBin(S);
    printf("Ep  ");
    PrintBin(Ep);
    printf("Mp  ");
    PrintBin(Mp);
    
    double E , M;
    double r = 0;
    
    if(Ep==0)
    {
        E = 1.0-pow(2.0,e-1)+1;
        M = 1.0 * Mp / pow(2.0,m);
        
    }
    else if(~Ep!=0)
    {
        E = Ep-pow(2.0,e-1)+1;
        M = 1 + 1.0 * Mp / pow(2.0,m);
        //r = pow(-1.0, S) * pow(2.0, E) * M;
    }
    else
    {
        // if(Mp==0)
            // r = inf;
        // else
            // r = nan;
        assert(0);
    }
    
    printf("M  ");
    PrintBin(*(__int64*)&M);
    
    r = pow(-1.0, S) * pow(2.0, E) * M;
    
    printf("%.15g\n", r);
    assert(fabs(r-a)<1e-5);
}

void main()
{
    Test1();
    Test2();
    Test3();
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.