如何避免在C ++中浮点运算的舍入问题? [英] How to get around rounding issues in floating point arithmetic in C++?

查看:168
本文介绍了如何避免在C ++中浮点运算的舍入问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到一些问题,浮点运算不准确。我试图基于一个加权公式计算得分,其中每个输入变量的权重大约是下一个重要的20倍。然而,输入是实数,因此我最后使用double来存储结果。下面的代码有丢失E1和E2之间的区别的问题。

Im running into some issues with floating point arithmetic not being accurate. I'm trying to calculate a score based on a weighted formula where every input variable weighs about as much as 20 times the next significant one. The inputs however are real numbers, so I ended up using a double to store the result. The code below has the problem of losing the difference between E1 and E2.

这段代码是性能敏感的,所以我需要找到一个有效的答案这个问题。我想到将我的输入乘以一百,然后使用一个int(因为那将是精确到足够我认为),但我怀疑这是最好的解决方案,因此的问题。

This code is performance sensitive, so I need to find an efficient answer to this problem. I thought of multiplying my inputs by a hundred and then using an int (since that would be precise enough I think), but I doubt that is the best solution, hence the question.

#include <iostream>

int main()
{
    double score1, score2;
    float a  = 2.75 ;
    float b  = 5.25 ;
    float c  = 5.25 ;
    float d  = 2.75 ;
    float E1 = 3    ;
    float E2 = 6    ;

    score1 = 20 * b - 1 * a + 0.05 * d  /* - 0.0025 * c*/ + 0.0001 * E1 ;
    score2 = 20 * b - 1 * a + 0.05 * d  /* - 0.0025 * c*/ + 0.0001 * E2 ;

    std::cout << score1 << std::endl;
    std::cout << score2 << std::endl;

    std::cin.get();
    return 0;
}

//ouputs:
//102.388
//102.388


推荐答案


  1. 您不是输出整个值,使用 cout< setprecision(number_of_digits)< score1<< endl;

  2. 您的分数计算需要多少有效数字?

这篇关于如何避免在C ++中浮点运算的舍入问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆