import re
def nearest( x, Max09 = 2, digits=25 ):
s = ('{val:.{dig}f}'.format( dig=digits, val=x ) ).split('.')
rnd = 0
if len(s) < 2 or s[1] == '0':## input is integer xyz or float of type xyz.
out = int( x )
else:
s0, s9 = Max09*'0', Max09*'9'
splitter = '{}|{}'.format( s0, s9)
body = s[0]
p0, p9 = s[1].find(s0), s[1].find(s9) ### returns -1 if nothing is found
tail = re.split( splitter, s[1] )[0]
out = int( body + tail )
if p9 > -1 and ( p9 < p0 or p0 < 0 ):
rnd = 1
return out + rnd
a = 7.999998560066533
b = 1.5999999991220535
c = 1.2799999997163347
d = 1233
e = 19935
f = 1.6000000000123
g = 10006.6000000000123
h = 500001.0
print nearest( a )
print nearest( b )
print nearest( c )
print nearest( d )
print nearest( e )
print nearest( f )
print nearest( g )
print nearest( h )
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]
^{} 告诉您,给定参数
rel_tol
和abs_tol
,两个floats
是否接近。默认设置为^{} 将直接跳到下一个整数,它可能远远超出这些公差。你知道吗
将
abs_tol
设置为<0.5
将使isclose
True
成为您在round
上使用过的内容:由于使用字符串操作的解决方案似乎还可以,下面是一个简短的解决方案:
只是提供:
编辑
正如@gc7所正确指出的那样,上述解决方案忽略了值稍大的情况。这使得代码有点复杂,但仍然很好。你知道吗
提供:
连续分数是很强大的。也许这是一个小的过度,但它的工作。你知道吗
给予:
相关问题 更多 >
编程相关推荐