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

cmath and math.h giving different answers

本文关键字:答案 math cmath      更新时间:2023-10-16

当我在浮点数上使用cmath和math中的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
}

为什么会发生这种情况?两个库实现atan的方式不同吗?

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