cmath和math.h给出了不同的答案

时间:2013-12-11 00:35:18

标签: c++ floating-point

当我使用cmath的atan函数和浮点数的数学时,我似乎得到了不同的答案:

#include <cmath>  
#include <math.h>                                                                              

#include <iostream>                                                             
#include <iomanip>                                                              

int main() {                                                                
    std::cout << std::setprecision(20) << atan(-0.57468467f) << std::endl;   
    std::cout << std::setprecision(20) << std::atan(-0.57468467f) << std::endl;  

    // I get:
    // -0.52159727580733605823
    // -0.52159726619720458984
}

为什么会这样?两个库是否以不同方式实现?

1 个答案:

答案 0 :(得分:7)

math.h的{​​{1}}取一个double并返回一个double,但atan被重载,因此float参数(如此处所用)将用作float和产生浮动结果。因此,输出的差异来自使用两种不同的浮点类型。要使它们使用相同的类型,请删除数字末尾的cmath或将第一个f更改为atan

相关问题