zoukankan      html  css  js  c++  java
  • boost之multiprecision

    multiprecision

    boost中提供的高精度库,支持高精度整型,浮点型等。并且提供统一的接口模板,只需要指定对应的后端类型即可实现对应类型的高精度计算:

    boost::multiprecision::number<XX_backend>
    

    cpp_int_backend

    提供高精度整型后端类型,需引入头文件#include <boost/multiprecision/cpp_int.hpp>

    template <unsigned MinBits = 0,
              unsigned MaxBits = 0,
              cpp_integer_type SignType = signed_magnitude,
              cpp_int_check_type Checked = unchecked,
              class Allocator = std::allocator<limb_type> >
    class cpp_int_backend;
    
    • MinBits:底层整型占用的最少位宽
    • MaxBits:底层整型占用的最大位宽
    • SignType:有符号整型还是无符号整型(任意精度的整型只能为signed!)
    • Checked:当发生数值溢出,从字符串转换失败,对负数进行位运算是否抛出异常
    • Allocator:内存分配器,当MinBits==MaxBits时,定义为void,表示不需要动态内存分配

    cpp_int中无符号型用二进制补码表示,有符号型用原码表示,并且额外用一位来表示符号;不允许任意精度的无符号整型也是因为二进制补码表示需要基于定长的精度。

    cpp_int使用示例

    有符号数为原码表示,并且额外用一个位表示符号:

    int main() {
        std::cout << "uint128 max: " << std::numeric_limits<boost::multiprecision::uint128_t>::max() << std::endl;
        std::cout << "int128 max: " << std::numeric_limits<boost::multiprecision::int128_t>::max() << std::endl;
        std::cout << "int128 min: " << std::numeric_limits<boost::multiprecision::int128_t>::min() << std::endl;
    
        return 0;
    }
    

    当有符号数转换为无符号数,先是按位截断,再对无符号数的二进制补码求负数:

    int main() {
        auto s = std::numeric_limits<boost::multiprecision::int128_t>::min();
        auto u = (boost::multiprecision::uint128_t)s;
    
        std::cout << "s: " << s << std::endl;
        std::cout << "u: " << u << std::endl;
    
        return 0;
    }
    

  • 相关阅读:
    Insus Meta Utility
    The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine.
    Insus Binary Utility
    asp.net实现文件下载功能
    Column 'Column Name' does not belong to table Table
    程序已被编译为DLL,怎样去修改程序功能
    如何在Web网站实现搜索功能
    如何把数据流转换为二进制字符串
    Asp.net更新文件夹的文件
    如何显示中文月份
  • 原文地址:https://www.cnblogs.com/HachikoT/p/13728343.html
Copyright © 2011-2022 走看看