• 主流架构(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或分数类。

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

    1. #include
    2. // fVal 原始浮点
    3. // iPoint 保留精度(末尾将清零)
    4. double getVal1(const double fVal, const int iPoint) {
    5. double factor = pow(10.0, iPoint);
    6. return floor(fVal * factor) / factor;
    7. }
    8. double getVal2(const double fVal, const int iPoint) {
    9. double factor = pow(10.0, iPoint);
    10. return round(fVal * factor) / factor;
    11. }
    12. double getVal3(const double fVal, const int iPoint)
    13. {
    14. double multiplier = 1.0;
    15. int i;
    16. // Calculate the multiplier based on the number of decimal places to keep
    17. for (i = 0; i < iPoint; i++) {
    18. multiplier *= 10.0;
    19. }
    20. // Multiply the original value by the multiplier and round it to the nearest integer
    21. int roundedValue = (int)(fVal * multiplier + 0.5);
    22. // Divide the rounded value by the multiplier to get the final result
    23. double result = roundedValue / multiplier;
    24. return result;
    25. }

  • 相关阅读:
    【聚类】DBCAN聚类
    16. Docker容器监控CAdvisor+InfluxDB+Granfana
    Centos7部署Python3环境
    游戏中的概率实现
    系统安装(一)CentOS 7 本地安装
    2022-08-02 mysql/stonedb慢SQL-Q18-内存使用暴涨分析
    无感刷新 token
    ES6新特性:变量的解构赋值
    RHCSA之date命令
    linux 文件锁
  • 原文地址:https://blog.csdn.net/wangningyu/article/details/133998359