主流架构(gcc、msvc、x86、x64、arm)中double与float浮点数保留精度(末尾清零)

编程入门 行业动态 更新时间:2024-10-19 08:48:50

主流架构(gcc、msvc、x86、x64、arm)中double与float浮点数保留精度(<a href=https://www.elefans.com/category/jswz/34/1771224.html style=末尾清零)"/>

主流架构(gcc、msvc、x86、x64、arm)中double与float浮点数保留精度(末尾清零)

​​​​​​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;
}

更多推荐

主流架构(gcc、msvc、x86、x64、arm)中double与float浮点数保留精度(末尾清零)

本文发布于:2023-12-03 07:29:59,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1652679.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:末尾   精度   架构   清零   主流

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!