首页 > C/C++ math.h中的函数传相同参数进去返回的值一定相同吗?

C/C++ math.h中的函数传相同参数进去返回的值一定相同吗?

我写的是C++

我希望对一些向量按其方向排序。我用下面的struct存向量

struct V { double x, y };

写下面的比较函数

inline bool operator<(const V &a, const V &b)
{
    return atan2(a.y,a.x)<atan2(b.y,b.x);
}

我把它传进std::sort里,然后排序过程中越界了。具体数据较大,不便分析。

然后我把V改成下面这样,并写一个构造函数

struct V
{
    double x, y, t;
    V(double _x, double _y) : x(_x), y(_y), t(atan2(y,x)) {}
};

比较函数改成

inline bool operator<(const V &a, const V &b)
{
    return a.t<b.t;
}

这样就没问题了。

我原来认为atan2就算计算有误差,传相同的参数进去也应该返回相同的值。上面的情况意味着不是这样吗?还是有别的什么问题?

以下为更新内容

我又做了如下实验,更没有头绪

代码:

#include<cmath>
#include<iostream>
using namespace std;

int main()
{
    int x=-3, y=7;
    double tmp=atan2(y,x);
    cout << (tmp==atan2(y,x)) << endl;
    double tmp2=atan2(y,x);
    cout << (tmp==tmp2) << endl;
    return 0;
}

输出:

0
1


应该是和下面一样的问题,加了-ffloat-store就好了。用-O0也不会错。
http://stackoverflow.com/questions/7517588/different-floating-point-result-with-optimization-enabled-compiler-bug


在构造struct的时候 x,y成员变量初始化一下吧..

【热门文章】
【热门文章】