如何在Python中执行精确的计算,而不考虑输入类型?

2024-06-16 11:28:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要以尽可能高的精度进行计算,不管传递的参数是整数、浮点还是任何数字。我可以这样想:

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

我可以看到一些问题:1)我认为我需要转换输入,而不是转换结果来工作2)看起来很难看(第一个操作是多余的C样式声明)。在

我如何以最高可用精度执行所有计算,然后以最高可用精度(即IMO)存储结果数字浮点数64)?


Tags: importnumpy声明参数foodefasnp
2条回答

可以声明变量,但可以尝试将其强制为预期类型

import numpy as np
def foo(*args):
    x, y, z = map(np.longdouble, args)
    return x + y * z

foo(0.000001,0.000001, 0.00000000001)

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

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位浮点,只需将返回值转换为: 回油浮子(a)

相关问题 更多 >