如何获得最大的精度? (Python-十进制) [英] How to get largest possible precision? (Python - Decimal)

查看:229
本文介绍了如何获得最大的精度? (Python-十进制)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将 Decimal 类用于需要精确度的操作.

I'm using the Decimal class for operations that requires precision.

我想使用最大可能"的精度.有了这个,我的意思是程序运行所在的系统可以处理的精确度.

I would like to use 'largest possible' precision. With this, I mean as precise as the system on which the program runs can handle.

要设置一定的精度很简单:

To set a certain precision it's simple:

import decimal
decimal.getcontext().prec = 123 #123 decimal precision

我试图找出'Decimal'类可以计算的最大精度:

I tried to figure out the maximum precision the 'Decimal' class can compute:

print(decimal.MAX_PREC)
>> 999999999999999999

因此,我尝试将精度设置为最大精度(知道它可能无法工作..):

So I tried to set the precision to the maximum precision (knowing it probably won't work..):

decimal.getcontext().prec = decimal.MAX_PREC

但是,当然,这会引发内存错误(除法运算)

But, of course, this throws a Memory Error (on division)

所以我的问题是:如何计算当前系统可以处理的最大精度?

So my question is: How do I figure out the maximum precision the current system can handle?

其他信息:

import sys
print(sys.maxsize)
>> 9223372036854775807

推荐答案

尝试执行此操作是一个错误.在一个问题上提高精度是吸引新手浮点运算的诱人陷阱,但它没有那么大的用处,尤其是在这种极端情况下.

Trying to do this is a mistake. Throwing more precision at a problem is a tempting trap for newcomers to floating-point, but it's not that useful, especially to this extreme.

您的操作实际上并不需要最大可能"的精度,即使这是一个定义明确的概念.他们要么需要精确的算术,在这种情况下,完全不正确的工具是c,而您应该研究像c1或符号计算之类的东西,或者它们不需要那么多的精度,而您应该确定您实际需要多少精度并使用它.

Your operations wouldn't actually require the "largest possible" precision even if that was a well-defined notion. Either they require exact arithmetic, in which case decimal.Decimal is the wrong tool entirely and you should look into something like fractions.Fraction or symbolic computation, or they don't require that much precision, and you should determine how much precision you actually need and use that.

如果您仍然想解决所有可能的精度问题,那么实际的精度取决于您正在执行的数学类型以及要存储在其中的多少个荒谬的精确数字一次记忆.这可以通过分析程序和Decimal对象的内存需求来确定,或者可以将精度作为参数并通过二进制搜索来寻找不会导致崩溃的最大精度.

If you still want to throw all the precision you can at your problem, then how much precision that actually is will depend on what kind of math you're doing, and how many absurdly precise numbers you're attempting to store in memory at once. This can be determined by analyzing your program and the memory requirements of Decimal objects, or you can instead take the precision as a parameter and binary search for the largest precision that doesn't cause a crash.

这篇关于如何获得最大的精度? (Python-十进制)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆