【习题 3-12 UVA - 11809】Floating-Point Numbers

本文介绍了一种处理特定数学算法中精度问题的方法。通过使用对数转换和长双精度浮点数来避免计算误差,并给出了具体的实现代码示例。

【链接】 我是链接,点我呀:)
【题意】


在这里输入题意

【题解】


\(A*10^B = temp[M]*2^{2^E-1}\)
两边取一下对数
得到
\(lg_A+B = lg_{temp[M]} + (2^E-1)*lg_2\)
这样就不至于算不出来啦。
打个表就好
防止爆精度。
加个long double.

【代码】

#include <bits/stdc++.h>
using namespace std;

string s;
long double two[20];
long double temp[20];
long long temp2[70];
long double ans[100][100];

int main(){
    #ifdef LOCAL_DEFINE
        freopen("F:\\c++source\\rush_in.txt", "r", stdin);
    #endif
    two[1] = 0.5;
    for (int i = 2;i <= 12;i++){
        two[i] = two[i-1]*0.5;      
    }
    temp[0] = two[1];
    for (int i = 1;i <= 9;i++) temp[i] = temp[i-1] + two[i+1];  
    
    temp2[0] = 1;
    for (int i = 1;i <= 30;i++) temp2[i] = temp2[i-1] * 2;
    
    for (int i = 0;i <= 9;i++){
        double M = temp[i];
        for (int j = 1;j <= 30;j++){
            ans[i][j] = log10(M) + (temp2[j]-1)*log10(2);           
        }
    }

    while (cin >> s){
        int len = s.size();
        for (int i = 0;i < len;i++) if (s[i]=='e') s[i] = ' ';
        long double A;
        long long B;
        stringstream ss(s);
        ss >> A >> B;
        if (A==0 && B==0) break;
        double temp = log10(A)+B;
        bool fi = false;
        for (int i = 0;!fi && i <= 9;i++)
            for (int j = 1;!fi && j <= 30;j++)
                if (fabs(ans[i][j]-temp)<1e-6){
                    printf("%d %d\n",i,j);
                    fi = true;
                }
    }
    return 0;
}

转载于:https://www.cnblogs.com/AWCXV/p/7819830.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值