无论输入类型如何,如何在Python中执行精确的计算? [英] How to perform precise calculations in Python, regardless of input types?

查看:75
本文介绍了无论输入类型如何,如何在Python中执行精确的计算?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要以尽可能最高的精度进行计算,无论传递的参数是整数,浮点数还是任何数字.我可以想到的一种方法是:

I need to make computations in the highest possible precision, regardless if the arguments passed are integers, floats or whatever numbers. One way I can think of this is:

import numpy as np
def foo(x, y, z)
a = (np.float64)0
a = x + y * z

我可以看到一些问题:1)我想我需要转换输入,而不是转换结果才能工作2)看起来很丑陋(第一个操作是多余的C样式声明).

I can see a couple of problems with this: 1) I think I need to convert the inputs, not the result for this to work 2)looks ugly (the first operation is a superfluous C-style declaration).

如何以最高的可用精度以Python方式执行所有计算,然后以最高的可用精度(即IMO numpy.float64)存储结果?

推荐答案

对我来说,显而易见的答案是十进制,除非函数需要非常快.

To me the obvious answer is Decimal, unless the function needs to be very fast.

import decimal
# set the precision to double that of float64.. or whatever you want.
decimal.setcontext(decimal.Context(prec=34))
def foo(x, y, z)
    x,y,z = [decimal.Decimal(v) for v in (x,y,z)] 
    a = x + y * z
    return a  # you forgot this line in the original code.

如果要使用常规的64位浮点数,则可以将返回值转换为该值: 返回float(a)

If you want a conventional 64bit float, you can just convert the return value to that: return float(a)

这篇关于无论输入类型如何,如何在Python中执行精确的计算?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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