python - 如何在乘以 10 的幂后找出最接近小数的整数
问题描述
我有一个最接近 8 的浮点数7.999999985666533
,我使用过它math.isclose
math.isclose(a, b)
但是对于浮点值,例如1.5999999991220535
最接近的整数是 2 但如果我将它与 相乘10 (10 ** 1)
,我得到 16 作为最接近的整数,这也是结果isclose
另一个例子:
1.2799999997163347
乘以后应该得到 128100 (10 ** 2)
有没有办法做到这一点?
解决方案
连续分数非常强大。也许这是一个小小的矫枉过正,但它的工作原理。
import numpy as np
def get_cont_fraction(x, depth=0, maxdepth=10, precision=1e-6):
if depth > maxdepth:
out = []
else:
assert x >= 0
out=[]
if not depth:
out += [ int(x) ] + get_cont_fraction( x - int( x ), depth=depth + 1, maxdepth=maxdepth, precision=precision)
elif x < precision :
out=[]
else:
out += [ int(1./ x) ] + get_cont_fraction(1. / x - int( 1. / x ), depth=depth + 1, maxdepth=maxdepth, precision=precision)
return out
def get_fraction(inList):
num = inList[-1]
den = 1
testList = inList[:-1:]
testList = testList[::-1]
for a in testList:
num , den = a * num + den, num
return ( num, den )
if __name__ == "__main__":
a = get_fraction( get_cont_fraction( 1.5999999991220535 ) )
print a
print a[0]*1./a[1]
a = get_fraction( get_cont_fraction( 1.2799999997163347 ) )
print a
print a[0]*1./a[1]
给予:
>> (8, 5)
>> 1.6
>> (32, 25)
>> 1.28
推荐阅读
- android - 使用 PassportJS 响应本机社交登录
- ios - Apple Silicon M1 Mac Mini 上的 Flutter:iOS SIM 错误
- scala - 杰克逊用 $ 符号读取节点字段
- npm - 为什么每次我使用 npm 或 yarn 安装包时,它都会安装所有依赖项?
- rust - 迭代器表示任意行为
- javascript - IOS SAP Hybrid/Native 移动应用程序中的 ajax GET 调用中的禁止错误
- python - NN 如何理解哪个类对应于哪个输出节点?反过来,我们作为人们如何识别概率对应的内容?
- python - 为什么某些动画 GIF 会在 Pillow 上显示故障区域?
- vue.js - 插入数据正在工作,但是当我更新数据时,它会给出一个错误,即所有字段都是必需的,即使它有一个值。如何解决这个问题?
- python - 根据直方图计数选择数据