我的目标是将任何有理数作为函数的输入,并输出下一个整数,该整数是输入数的倍数。有没有一种方法来确定任何此类数字的有理表达式?(即 1.5 作为输入将输出 3(
如果您了解其背后的数学原理,则无需使用蛮力循环。您可以计算使给定数字成为整数所需的 10 的幂,首先从数字的指数中推导它,然后通过将数字除以两者的最大公约数来计算数字与上述 10 的幂之间的最小公倍数:
from math import gcd
from decimal import Decimal
def whole_multiple(n):
power = 10 ** -n.as_tuple().exponent
n *= power
return n // gcd(int(n), power)
因此:
whole_multiple(Decimal('-4.4'))
返回:
-22
请注意,您必须向函数传递一个decimal.Decimal
对象,以便它计算指数并避免浮点近似误差。
你可以像这样缓慢而稳定地做到这一点:
def find_multiple(num):
new_num = num
while True: # until you hit a break statement
new_num = round(new_num + num, 3) # add the original number to the current number (next multiple), round because floating points are weird
if new_num.is_integer(): # check if that is a whole number
print(new_num) # if so print and break the loop
break
例:
>>> def find_multiple(num):
... new_num = num
... while True:
... new_num = round(new_num + num, 3)
... if new_num.is_integer():
... print(new_num)
... break
...
>>> find_multiple(1.5)
3.0
>>> find_multiple(1.9)
19.0
>>> find_multiple(45.123)
45123.0
你可以试试这个。我不确定答案是否正确!!.但如果它有效,我相信非常有效的解决方案。
def nextMultiple(x):
'''
converting x to integer by multiplying by powers of 10
eg: 1.5 as 15.0 = 1.5 * 10
eg: 1.234 as 1234 = 1.234 * 1000
'''
m = len(str(x).split('.')[1])
y = x * 10**(m)
ans = y
'''
finding all prime factors of y and checking for condition to find the answer
'''
for i in range(2, int(y**0.5) + 1):
if y % i == 0:
c = round(i / x, m)
if c == int(c) and i > x:
ans = min(ans, i)
o = y / i
c = round(o / x, m)
if c == int(c) and o > x:
ans = min(ans, o)
return ans
1.5 -> 3
3.13 -> 313.0
1.75 -> 7
10.1 -> 101.0