math.log 的问题
issue with math.log
我一直在尝试使用我的 Python 编辑器使用数学库编写此程序。本质上,我试图让用户输入任何正数,然后给定他们的正数显示 2^n 的第一个幂的输出等于或大于他们的输入。
例如我的代码在用户输入 256 时工作,输出变为
"256.0 is the first power greater than or equal to 256".
然而当用户输入数字如248时,输出变成
" 495.99 is the first power greater than or equal to 248".
这是我不想要的,我需要大于 248 的第一个幂来显示,因此正确的输出应该是
"256 is the first power greater than or equal to 248".
我已经编写了下面的代码,并愿意接受任何可以改进代码的建议。
import math
number= int(input("Enter any positive integer value greater : "))
assert number >=2, "Number must be greater than or equal to 2"
x=math.log2(number)
y=math.pow(2,x)
print(x)
print(y)
if y == number:
print(y, "is the first power greater than or equal to", number)
elif number != y:
z=x+1
k=math.floor(z)
a=math.pow(2,k)
print(a, "is the first power greater than or equal to", number)
这里有一些伪代码可以帮助您入门:
//n = user input
//int power = 0;
//while(2^power < n){power++}
//output "power" variable to system.
您需要将 z 向下舍入为整数。为此使用 math.floor()。
问题是您要计算 2 的非整数次方,因为您要计算 2^(x+1) 而 x 不是整数。您只需将 x 向上舍入到最接近的整数而不是加 1,
也是如此
z = math.ceil(x)
或者类似的东西。
我一直在尝试使用我的 Python 编辑器使用数学库编写此程序。本质上,我试图让用户输入任何正数,然后给定他们的正数显示 2^n 的第一个幂的输出等于或大于他们的输入。 例如我的代码在用户输入 256 时工作,输出变为
"256.0 is the first power greater than or equal to 256".
然而当用户输入数字如248时,输出变成
" 495.99 is the first power greater than or equal to 248".
这是我不想要的,我需要大于 248 的第一个幂来显示,因此正确的输出应该是
"256 is the first power greater than or equal to 248".
我已经编写了下面的代码,并愿意接受任何可以改进代码的建议。
import math
number= int(input("Enter any positive integer value greater : "))
assert number >=2, "Number must be greater than or equal to 2"
x=math.log2(number)
y=math.pow(2,x)
print(x)
print(y)
if y == number:
print(y, "is the first power greater than or equal to", number)
elif number != y:
z=x+1
k=math.floor(z)
a=math.pow(2,k)
print(a, "is the first power greater than or equal to", number)
这里有一些伪代码可以帮助您入门:
//n = user input
//int power = 0;
//while(2^power < n){power++}
//output "power" variable to system.
您需要将 z 向下舍入为整数。为此使用 math.floor()。
问题是您要计算 2 的非整数次方,因为您要计算 2^(x+1) 而 x 不是整数。您只需将 x 向上舍入到最接近的整数而不是加 1,
也是如此z = math.ceil(x)
或者类似的东西。