涉及到double 值比较的eps 应用

来源:互联网 发布:understand mac 编辑:程序博客网 时间:2024/06/07 10:08

在一般涉及到double 类型变量计算的时候,精度损失是必然的。double 的有效数字只有16 位,在16 位之后的数字就乱七八糟了,再加上乘除、cmath 等头文件的计算,精度又要损失几位,用cfloat 头文件里的DBL_EPSILON 作为精度误差可能不太管事了。
所以我们可以自己设置一个精度常量eps,然后写几个inline 的比较函数,这里以1e-6 为例,要用的时候,用到哪个打哪个。最后再拿一题小练一下。

const double eps = 1e-6;inline bool zero(const double &x) {    return fabs(x) < eps;}inline bool equal(const double &x, const double &y) {    return fabs(x - y) < eps;}inline bool smaller(const double &x, const double &y) {    return !equal(x, y) && x < y;}inline bool larger(const double &x, const double &y) {    return !equal(x, y) && x > y;}

题目链接

51Nod 1080: 两个数的平方和

题意

给一个数N,将N 表示为2 个整数i, j的平方和(0ij),如果有多种表示,按照i 的递增序输出。其中N[1,109]

题解

i 从0 到N 跑,计算Ni2 的值,如果为整数,按大小放到set< pair< int, int>> 里面,再依次输出。

过题代码

#include <iostream>#include <cmath>#include <set>#include <algorithm>using namespace std;const double eps = 1e-6;inline bool equal(const double &x, const double &y) {    return fabs(x - y) < eps;}int main() {    int N;    double sq;    set<pair<int, int> > ans;    cin >> N;    sq = sqrt(N);    for(int i = 0; i < sq; ++i) {        double j = sqrt(N - i * i);        if(equal(j, floor(j))) {            int Min = min(i, (int)j);            int Max = max(i, (int)j);            ans.insert(make_pair(Min, Max));        }    }    if(ans.size() == 0) {        cout << "No Solution" << endl;    } else {        set<pair<int, int> >::iterator it;        for(it = ans.begin(); it != ans.end(); ++it) {            cout << it->first << " " << it->second << endl;        }    }    return 0;}
原创粉丝点击