std::floor函数的不同值用于具有相同值但不同类型的参数
different values of std::floor function for arguments with same value but different types
考虑以下内容:
#include <iostream>
#include <cmath>
int main()
{
using std::cout;
using std::endl;
const long double be2 = std::log(2);
cout << std::log(8.0) / be2 << ", " << std::floor(std::log(8.0) / be2)
<< endl;
cout << std::log(8.0L) / be2 << ", " << std::floor(std::log(8.0L) / be2)
<< endl;
}
输出
3, 2
3, 3
为什么输出不同?我在这里错过了什么?
这里还有代码板的链接:http://codepad.org/baLtYrmy
我在linux上使用gcc 4.5,如果这很重要的话。
当我添加这个时:
cout.precision(40);
我得到这个输出:
2.999999999999999839754918906642444653698, 2
3.00000000000000010039712117215771058909, 3
您打印的两个值非常接近,但并不完全等于3.0。std::floor
的本质是,对于非常接近的值,其结果可能会有所不同(从数学上讲,它是一个不连续函数(。
#include <iostream>
#include <cmath>
#include <iomanip>
int main()
{
using std::cout;
using std::endl;
const long double be2 = std::log(2);
cout << setprecision (50)<<std::log(8.0)<<"n";
cout << setprecision (50)<<std::log(8.0L)<<"n";
cout << setprecision (50)<<std::log(8.0) / be2 << ", " << std::floor(std::log(8.0) / be2)
<< endl;
cout << setprecision (50)<< std::log(8.0L) / be2 << ", " << std::floor(std::log(8.0L) / be2)
<< endl;
return 0;
}
输出为:
2.0794415416798357476579894864698871970176696777344
2.0794415416798359282860714225549259026593063026667
2.9999999999999998397549189066424446536984760314226, 2
3.0000000000000001003971211721577105890901293605566, 3
如果您在此处检查输出,您会注意到两个输出的精度略有差异。这些舍入误差通常在float&在执行floor()
时在这里加倍,并且出现的结果不是人们认为应该是的。
重要的是要记住两个属性Precision&使用浮点数或双位数时进行舍入。
你可能想在我的回答中阅读更多关于它的信息,这里,同样的推理也适用于这里。
扩展Als所说的内容-
在第一种情况下,您将一个8字节的双精度值除以一个16字节长的双精度。在第二种情况下,您将16字节长的双精度除以16字节长双精度。这导致了一个非常小的舍入误差,可以在这里看到:
cout << std::setprecision(20) << (std::log(8.0) / be2) << std::endl;
cout << std::setprecision(20) << (std::log(8.0L) / be2) << std::endl;
产生:
2.9999999999999998398
3.0000000000000001004
编辑说:在这种情况下,sizeof是你的朋友(查看精度的差异(:
sizeof(std::log(8.0)); // 8
sizeof(std::log(8.0L)); // 16
sizeof(be2); // 16
相关文章:
- 在 c++ 中的模板实例化中使用带有构造函数的类作为类型参数
- 如何解决一元"*"(有"字符")错误的无效类型参数?
- "std::shared_ptr":不是参数"_Ty"的有效模板类型参数
- 具有可变参数非类型参数的模板专用化
- 函数类型参数的模板参数推导
- PowerShell 使用结构类型参数调用 C++ DLL 的导出函数
- 对于非常量指针类型的参数,未调用具有常量指针模板类型参数的功能
- 为模板传递非类型参数 agument
- 为什么带有类型参数的运算符 () 可以应用于 result_of 上下文中的类型?
- 使用其他模板类型参数作为要在函数签名中使用的类型别名声明
- 如何避免具有相同类型参数的函数中的错误
- 将内置类型变量传递给只有一个类类型参数的"+"运算符函数时自动类型转换的构造函数
- c++非类型参数包扩展
- 如何实现对参数顺序不可知的std::same_as的广义形式(即对于两个以上的类型参数)
- 在不同的模板参数包之间分发非类型参数包
- 如何在使用容器和字符串时强制使用显式分配器类型参数
- 错误:一元"*"的类型参数无效(具有"int"):使用 mergesort 计算
- EXPECT_CALL具有 unique_ptr 引用类型参数的模拟函数
- 作为模板类型参数,为什么 type[N] 与其专用版本不匹配----模板<类 T>类 S<T[]>
- C++ 模板:重载时找不到基类类型参数方法