我必须使用 Python3(PyPy 实现)分析大量数据,其中我对相当大的浮点数进行一些操作,并且必须检查结果是否足够接近整数。
举个例子,假设我正在生成随机的数字对,并检查它们是否形成毕达哥拉斯三元组(是具有整数边的直角三角形的边):
from math import hypot
from pprint import pprint
from random import randrange
from time import time
def gen_rand_tuples(start, stop, amount):
'''
Generates random integer pairs and converts them to tuples of floats.
'''
for _ in range(amount):
yield (float(randrange(start, stop)), float(randrange(start, stop)))
t0 = time()
## Results are those pairs that results in integer hypothenuses, or
## at least very close, to within 1e-12.
results = [t for t in gen_rand_tuples(1, 2**32, 10_000_000) if …Run Code Online (Sandbox Code Playgroud) python precision pypy floating-accuracy double-double-arithmetic