浮点小数精度
Float Fractional Precision
float
在1.0f
和0.0f
之间有多少个精度位置,以便每个值都可以唯一表示?
例如,如果第一个小数float
不能表示0.13f
,那么答案是浮点只有1个精度位置。
std::numeric_limits<float>::digits10
发件人http://en.cppreference.com/w/cpp/types/numeric_limits/digits10
标准的32位IEEE 754浮点类型有一个24位小数部分(写入23位,隐含一位),这可能表明它可以表示7位小数(24*std::log10(2)为7.22),但相对舍入误差是不均匀的,一些具有7位小数的浮点值无法转换为32位浮点并返回:最小的正示例为8.589973e9,往返后变为8.589974e9。这些舍入误差在表示中不能超过一位,数字10计算为(24-1)*std::log10(2),即6.92。向下舍入得到值6。
第2版:这表明,对于任何浮点,数字不是7,而是只有6位,就像std::numeric_limits<float>::digits10
调用一样。
float orgF = 8.589973e9;
int i = orgF;
float f = i;
assert(f == orgF);
当往返行程更改值时,此将失败。
因此,如果我们只寻找1.0到0.0之间的数字,正的答案是7,因为有问题的最低正数是8.589973e9。
如果我正确理解你的问题,答案是6。
#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>
using namespace std;
int main() {
int i = 10; /* Number of distinct number after 1 place of decimal */
int k = 1; /* Number of decimal places */
for(;/* ever */;)
{
float prev = 0.0f;
for(int j = 1; j <= i; ++j)
{
stringstream ss;
ss << "0."; /* Prepare stream with 0. followed by k digit number with leading zeroes */
ss << setfill('0') << setw(k) << j;
float next; /* Read the number */
ss >> next;
if(prev == next) return 0; /* If previous number and current number can not be distinguished */
prev = next;
}
cout << "Works for " << k << " places" << endl;
i *= 10; /* 10 times more tests to be conducted for 1 more decimal places */
k++; /* Try for more decimal places */
}
return 0;
}
代码的作用
1.将精度设置为小数后1位2.将0.0与0.1、0.1与0.2进行比较……将0.8与0.9和0.9进行比较对于1.0,如果其中任何一个相等(不区分),则退出。否则打印作品1处。3.将精度设置为小数后2位4.比较0.00与0.01、0.01与0.02…0.98与0.99和0.99使用1.00,如果其中任何一个相等(不区分),则退出。否则印刷作品2处。5.对3位及以上的数字重复类似的步骤,除非退出
相关文章:
- 如何防止 c++ 在从浮点型转换为双精度型(不适用于 IO)时添加额外的小数?
- 为什么 std::cout 打印浮点数、双精度和长双精度到相同的小数精度?
- 打印双精度的整个非小数部分
- c++只关心2位小数,没有设置精度
- 有没有一种方法可以在不设置精度的情况下设置小数位数
- 将字符串转换为双精度,而字符串有 N 位小数,C++
- C++ std::流双精度值没有科学,也没有固定的小数计数
- 小数、双精度、整数等数据类型的范围
- 在C++中使用atof将带小数的字符串转换为双精度字符串
- 如何打印具有正确有效小数位数的C++双精度
- 如何在C++中计算10位小数精度的双变量
- 使用 C++ 中的按位运算隔离双精度的小数部分
- 基元浮点和双精度支持小数位数
- 如何在Qt中打印所有小数的双精度
- 双精度不能正确减去小数
- C++ 如何获取兰登数以及如何保存带有 ONY 两位小数的双精度
- 双精度-小数位数
- 为什么我的浮点值会丢失精度并丢弃小数?下面的代码示例
- 打印浮点精度为 2,但在C++中没有小数 (.)
- 浮点小数精度