Python 如何编写程序来显示;“结果太大”;当涉及非常大的计算时?
我尝试在图形计算器中计算32**(32**32),但程序挂起了。如何像字符串一样显示“太大的结果”,而不是挂起?Python 如何编写程序来显示;“结果太大”;当涉及非常大的计算时?,python,Python,我尝试在图形计算器中计算32**(32**32),但程序挂起了。如何像字符串一样显示“太大的结果”,而不是挂起? 我使用了以下函数 def result(text): global backend, frontend, backend_list, frontend_list try: backend_list.append(str(eval(backend))) backend=backend_list[-1] frontend_l
我使用了以下函数
def result(text):
global backend, frontend, backend_list, frontend_list
try:
backend_list.append(str(eval(backend)))
backend=backend_list[-1]
frontend_list.append(str(round(eval(backend),5)))
frontend=frontend_list[-1]
backend_list.clear()
backend_list.append(backend)
frontend_list.clear()
frontend_list.append(frontend)
text.delete(1.0, END)
text.insert(INSERT, frontend)
except ZeroDivisionError:
backend=frontend=""
text.delete(1.0, END)
text.insert(INSERT, "not defined")
except TypeError:
backend=frontend=""
text.delete(1.0, END)
text.insert(INSERT, "type error: presumably\ncomplex number or\nmissing operators")
except:
text.delete(1.0, END)
text.insert(INSERT, "error")
python这样做的问题是,python在技术上没有整数的大小限制。最终,您的计算机将用尽内存来尝试计算,但这将需要一段时间,计算机将挂起,直到它这样做 与整数不同,浮点数有大小限制。如果愿意,您可以将参数转换为浮点,并依靠内置的浮点行为为您完成工作:
try:
eval('float(32) ** 32 ** 32')
except OverflowError:
print("Result too large")
问题是,您依赖的是eval()
,这使您无法控制。如果你想让你的计算器真正灵活,你必须自己解码和解释这个表达式,是实现此目的的最佳方法,您可以结合使用ast.parse(您的\u输入)
和ast.walk(您的\u parse的结果)
逐个检查操作数并根据需要对其求值。这将很复杂,您需要仔细考虑如何实现它,但一个简单的解决方案可能是遍历树并将所有常量转换为浮点数,如果它们还没有:
import ast
...
def eval_ast(expr='32 ** 32 ** 32'):
# decompose into parsed elements
# if entered normally, expr() will be a hierarchy of AST objects. The top few
# are not useful to us:
# ast.Module (has attribute .body containing a list of the next level)
# ast.Expr (has attribute .value containing the next level)
# so we attempt to ignore them.
expr_obj = ast.Expression(ast.parse(expr).body[0].value)
# walk through the nodes in the AST and convert integers to floats
for node in ast.walk(expr_obj):
if isinstance(node, ast.Constant):
node.value = float(node.value)
# recompose back into an evaluatable expression
expr_eval = ast.fix_missing_locations(expr_obj)
exe = compile(expr_eval, filename="<string>", mode="eval")
return eval(exe)
您可以自定义它,并根据需要将其集成到计算器中。如果您需要更精确或更精确的控制,手动遍历AST表达式并自己计算每个步骤可能会更有用。显示这么大的数字有什么意义。它甚至不能存储在变量中您的实际目标是什么?您想将此结果写入文件?顺便说一句,这是一个荒谬的大数字。当用户输入32^32^32时,你的图形计算器就变成了普通的计算器,这并不奇怪。。。它只是显示“超出可接受范围的计算”或类似的内容。。。我想展示这样的东西问题是Python对其整数的大小没有固定的限制。知道它太多的唯一方法是,如果它试图计算它,则会填满内存。
>>> eval_ast('32 ** 32 ** 32')
Traceback (most recent call last):
...
OverflowError: (34, 'Result too large')
>>> eval_ast('2 ** 32')
4294967296.0