• c: investigate float


    #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();
    }
  • 相关阅读:
    阿里云盾证书服务助力博客装逼成功
    内容安全策略(CSP)_防御_XSS_攻击的好助手
    Spring-beans架构设计原理
    Httpclient核心架构设计
    第四章 数据类型—字典(dict)、集合(set)
    第三章 数据类型 — 列表(list)、元组(tuple)
    第三章 数据类型 — int、bool 和 str
    第二章 Python基础(二)
    pycharm快捷键
    第二章 Python基础(一)
  • 原文地址:https://www.cnblogs.com/cutepig/p/1956922.html
Copyright © 2020-2023  润新知