C++与 Python 精度对比

发布于 2024-09-26 00:25:45 字数 635 浏览 0 评论 0原文

尝试查找 num^num 的前 k 位数字的问题我用 C++ 和 Python

C++

long double intpart,num,f_digit,k;
cin>>num>>k;
f_digit= pow(10.0,modf(num*log10(num),&intpart)+k-1);
cout<<f_digit;

Python

(a,b) = modf(num*log10(num))
f_digits = pow(10,b+k-1)
print f_digits

输入

19423474 9

输出

C++    > 163074912
Python > 163074908

编写了相同的程序,我检查了结果,C++ 解决方案是准确的。 在http://www.wolframalpha.com/input/?i=19423474^19423474检查它

知道如何在Python中获得相同的精度吗???

编辑:我知道外部库包可以获得这种精度,但有任何原生解决方案吗???

Trying out a problem of finding the first k digits of a num^num I wrote the same program in C++ and Python

C++

long double intpart,num,f_digit,k;
cin>>num>>k;
f_digit= pow(10.0,modf(num*log10(num),&intpart)+k-1);
cout<<f_digit;

Python

(a,b) = modf(num*log10(num))
f_digits = pow(10,b+k-1)
print f_digits

Input

19423474 9

Output

C++    > 163074912
Python > 163074908

I checked the results the C++ solution is the accurate one.
Checked it at http://www.wolframalpha.com/input/?i=19423474^19423474

Any idea how can I get the same precision in Python ???

EDIT : I know about the external library packages to obtain this precision but any NATIVE solution ???

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

不甘平庸 2024-10-03 00:25:45

Decimal 是一个内置的 Python 类,可以正确处理浮点(以 10 为基数,而不是 IEEE 7somethingsomething 标准)。我不知道它是否支持对数等等。

编辑:它确实支持对数“以及所有这些”。

你可以也设置它的精度。默认为 28 个位置,但可以根据需要设置任意大小。将其视为小数的 BigInt。

Decimal is a built in python class that handles floating points correctly (as base 10, not as IEEE 7somethingsomething standard). I don't know if it supports logarithms and all that though.

Edit: It does indeed support logarithms "and all that".

You can set the precision of it as well. Default is 28 places, but it can be as large as you want. Think of it as a BigInt for decimals.

可是我不能没有你 2024-10-03 00:25:45

正如您所发现的,Python 浮点数在底层是双精度的。您将不得不求助于 C 代码或外部库,以获得更好的浮点精度。

GMP 库是一个很好的库,它有一个名为“GMPY”的 Python 包装器,可以在 PyPI 上找到

Python floats are doubles under the hood, as you discovered. You will have to resort to C code, or an external library, to get better floating-point precision.

The GMP library is a good one, and it has a python wrapper called 'GMPY', available on PyPI

绝不放开 2024-10-03 00:25:45

一般来说,我会这样做。然而,对于您的示例数字来说,它的执行速度似乎不够快。

num = 453
k = 9
result = num ** num

print str(result)[:k]
# Prints: '163111849'

In general, I would do it this way. However, it doesn't seem to perform anywhere near fast enough for your example numbers.

num = 453
k = 9
result = num ** num

print str(result)[:k]
# Prints: '163111849'
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文