Floating-Point Numbers( UVA - 11809,计算机浮点数模拟)

本文探讨了计算机中浮点数的存储方式,通过E-M方法解析浮点数的阶码和尾数位数,并提供了一种算法来确定给定浮点数形式下M和E的具体数值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一.题目链接:

UVA-11809

二.题目大意:

计算机常用 E — M 的方法保存浮点数.               

E:阶码位数   M:尾数位数.          0 ≤ M ≤ 9, 1 ≤ E ≤ 30.

例如当 E == 6 && M == 8,则浮点数为  0.111111111{_{2}}^{} × 2^{111111_2} .

这个数转换成 10 进制之后就是 0.998046875 × 2^{63}  .

用 A × 10^{B} 的形式则表示为 9.205357638345294 × 10^{18} .

现给出一个形式为 AeB (0 < A < 10)的最大浮点数,试求出 M 和 E .

三.分析:

易得浮点数 :     A\times 10^{B} == (1 - \frac{1}{2^{M + 1}}) \times 2^{2^{E} - 1} 

两边取对数得:  lgA + B == lg(1 - \frac{1}{2^{M + 1}}) + (2^{E} - 1)\times lg2  

 \because 0 < A < 10

 \therefore lgA < 1

又 B 为整数

∴ lgA 为浮点数的小数部分

\therefore B == [ lg(1 - \frac{1}{2^{M + 1}}) + (2^{E} - 1)\times lg2]

   A == lg(1 - \frac{1}{2^{M + 1}}) + (2^{E} - 1)\times lg2 - B

四.代码实现:

#include <set>
#include <map>
#include <ctime>
#include <queue>
#include <cmath>
#include <stack>
#include <vector>
#include <cstdio>
#include <sstream>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#define eps 1e-4
#define PI acos(-1.0)
#define ll long long int
using namespace std;

const int M = 40;
double A[M][M];
int B[M][M];

void init()
{
    for(int m = 0; m < 10; ++m)
    {
        for(int e = 1; e < 31; ++e)
        {
            double tm = 1 - 1.0 / (1 << (m + 1));
            double te = (1 << e) - 1;
            double t = log10(tm) + te * log10(2);
            B[m][e] = t;
            A[m][e] = pow(10, t - B[m][e]);
        }
    }
}

int main()
{
    init();///打表
    string s;
    while(cin >> s && s != "0e0")
    {
        double a;
        int b;
        s[s.find('e')] = ' ';
        stringstream ss(s);
        ss >> a >> b;///读入处理
        for(int m = 0; m < 10; ++m)
        {
            for(int e = 1; e < 31; ++e)
            {
                if(b == B[m][e] && fabs(a - A[m][e]) < eps)
                    printf("%d %d\n", m, e);
            }
        }
    }
    return 0;
}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值