gpt4 book ai didi

python - 如何以一定的精度存储数字?

转载 作者:行者123 更新时间:2023-11-30 05:43:34 25 4
gpt4 key购买 nike

我想做的是计算一个数 N 的平方根,然后我们必须用 P 正确的小数值来存储这个平方根。例如

  Lets,N=2 and P=100

//I want to store square root till P correct decimal values
like storing
1.41421356237309504880...till 100 values

EDIT - 最初我问的是专门针对 c++ 的问题,但正如 vsoftco 所说,如果没有 boost,c++ 几乎不可能做到这一点。所以我也标记了 python并没有删除 c++ 标签,希望在 C++ 中得到正确答案

最佳答案

C++ 使用 floating-point类型(例如 floatdouble 等)来存储浮点值并执行浮点运算。这些类型的大小(直接影响它们的精度)是实现定义的(通常你不会得到超过 128 位的精度)。此外,精度是一个相对术语:当你的数字增长时,你的精度会越来越低。

因此,回答您的问题:使用标准 C++ 类型不可能以任意精度存储数字。您需要为此使用多精度库,例如Boost.Multiprecision .

使用 Boost.Multiprecison 的示例代码:

#include <boost/multiprecision/cpp_dec_float.hpp>
#include <iostream>

int main()
{
using namespace boost::multiprecision;
typedef number<cpp_dec_float<100> > cpp_dec_float_100; // 100 decimal places

cpp_dec_float_100 N = 2;
cpp_dec_float_100 result = sqrt(N); // calls boost::multiprecision::sqrt
std::cout << result.str() << std::endl; // displays the result as a string
}

如果你使用 Python,你可以使用 decimal 模块:

from decimal import *

getcontext().prec = 100
result = Decimal.sqrt(Decimal(2))
print("Decimal.sqrt(2): {0}".format(result))

关于python - 如何以一定的精度存储数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30144323/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com