当前位置:首页 > 编程笔记 > 正文
已解决

主流架构(gcc、msvc、x86、x64、arm)中double与float浮点数精度处理

来自网友在路上 165865提问 提问时间:2023-10-25 16:30:57阅读次数: 65

最佳答案 问答题库658位专家为你答疑解惑

​​​​​​float 是单精度浮点数,内存占4个字节,有效数字8位,表示范围是 -3.40E+38~3.40E+38。

double 是双精度浮点数,内存占8个字节,有效数字16位,表示范是-1.79E+308~-1.79E+308。

    C和C++标准没有指定EDCOX1、1、EDCOX1、0和EDCOX1×9的表示。这三个都有可能实现为IEEE双精度。然而,对于大多数架构(gcc、msvc、x86、x64、arm),float实际上是一个IEEE单精度浮点数(binary32),double是一个IEEE双精度浮点数(binary64)。

    有时甚至double也不够精确,因此有时我们有long double1(上面的例子在Mac上给出了9.00000000000000066),但所有浮点类型都有舍入错误,因此,如果精度非常重要(例如,货币处理),则应使用int或分数类。

    浮点会由于精度问题,导致无法直接做 != 比较,下面是一个主流架构下,优化处理浮点精度的函数:

#include <cmath>// fVal		原始浮点
// iPoint	保留精度(末尾将清零)
double getVal1(const double fVal, const int iPoint) {double factor = pow(10.0, iPoint);return floor(fVal * factor) / factor;
}double getVal2(const double fVal, const int iPoint) {double factor = pow(10.0, iPoint);return round(fVal * factor) / factor;
}double getVal3(const double fVal, const int iPoint) 
{double	multiplier = 1.0;int 	i;// Calculate the multiplier based on the number of decimal places to keepfor (i = 0; i < iPoint; i++) {multiplier *= 10.0;}// Multiply the original value by the multiplier and round it to the nearest integerint roundedValue = (int)(fVal * multiplier + 0.5);// Divide the rounded value by the multiplier to get the final resultdouble result = roundedValue / multiplier;return result;
}

查看全文

99%的人还看了

猜你感兴趣

版权申明

本文"主流架构(gcc、msvc、x86、x64、arm)中double与float浮点数精度处理":http://eshow365.cn/6-24285-0.html 内容来自互联网,请自行判断内容的正确性。如有侵权请联系我们,立即删除!