[关闭]
@Dmaxiya 2020-08-24T23:42:35.000000Z 字数 1544 阅读 1095

涉及到 double 值比较的 eps 应用

博文


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

  1. const double eps = 1e-6;
  2. inline bool zero(const double &x) {
  3. return fabs(x) < eps;
  4. }
  5. inline bool equal(const double &x, const double &y) {
  6. return fabs(x - y) < eps;
  7. }
  8. inline bool smaller(const double &x, const double &y) {
  9. return !equal(x, y) && x < y;
  10. }
  11. inline bool larger(const double &x, const double &y) {
  12. return !equal(x, y) && x > y;
  13. }

题目链接

51Nod 1080: 两个数的平方和

题意

给一个数 ,将 表示为 2 个整数 的平方和 ,如果有多种表示,按照 的递增序输出。其中

题解

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

过题代码

  1. #include <iostream>
  2. #include <cstdio>
  3. #include <cstdlib>
  4. #include <cmath>
  5. #include <climits>
  6. #include <cstring>
  7. #include <string>
  8. #include <vector>
  9. #include <list>
  10. #include <queue>
  11. #include <stack>
  12. #include <map>
  13. #include <set>
  14. #include <bitset>
  15. #include <algorithm>
  16. #include <functional>
  17. #include <iomanip>
  18. using namespace std;
  19. #define LL long long
  20. const double eps = 1e-6;
  21. inline bool equal(const double &x, const double &y) {
  22. return fabs(x - y) < eps;
  23. }
  24. int main() {
  25. #ifdef LOCAL
  26. freopen("test.txt", "r", stdin);
  27. // freopen("out.txt", "w", stdout);
  28. #endif // LOCAL
  29. ios::sync_with_stdio(false);
  30. int N;
  31. double sq;
  32. set<pair<int, int> > ans;
  33. cin >> N;
  34. sq = sqrt(N);
  35. for(int i = 0; i < sq; ++i) {
  36. double j = sqrt(N - i * i);
  37. if(equal(j, floor(j))) {
  38. int Min = min(i, (int)j);
  39. int Max = max(i, (int)j);
  40. ans.insert(make_pair(Min, Max));
  41. }
  42. }
  43. if(ans.size() == 0) {
  44. cout << "No Solution" << endl;
  45. } else {
  46. set<pair<int, int> >::iterator it;
  47. for(it = ans.begin(); it != ans.end(); ++it) {
  48. cout << it->first << " " << it->second << endl;
  49. }
  50. }
  51. return 0;
  52. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注