Python 如何找到小于x的最大整数
在本文中,我们将向您展示如何在Python中找到小于x的最大整数。
最大整数函数 [X] 指的是实数x的最接近和最小整数部分。它也被称为 X-floor 。
[x]=the largest integer less than or equal to x.
一般情况下
如果n≤X < n+1,则(n∈整数)=> [X] = n。这意味着如果X位于[n,n+1)之间,则X的最大整数函数将为n。
X | [X] |
---|---|
0<=x<1 | 0 |
1<=x<2 | 1 |
2<=x<3 | 2 |
在给定的表中,我们总是对值进行向下取整。当区间形式为[n,n+1)时,最大整数函数的值为n,其中n是整数。
- 0≤x <1始终位于区间[0,0.9)中,因此X的最大整数函数为0。
- 1≤x <2始终位于区间[1,1.9)中,因此X的最大整数函数为1。
- 2≤x <3始终位于区间[2,2.9)中,因此X的最大整数函数为2。
最大整数函数的性质
- 如果X是整数, [X]=X 成立。
- [X+Y]≥[X]+[Y] ,这表明X和Y的总和的最大整数等于X的最大整数和Y的最大整数。
- 如果[f(X)]≥I,则f(X)≥I。
- 如果[f(X)]≤I,则f(X)<I+1。
- [-X]=-[X],如果X属于整数。
- [-X]=-[X]-1,如果X不是整数。
它通常被称为阶梯函数或X的底部。
使用math.floor()方法的最大整数函数
math.floor() 方法将一个值向下取整,如果有必要的话,并得到结果。
Python中的math模块提供了一系列可以使用该模块轻松完成的数学运算。 math.floor() 函数产生不大于x的最大整数。如果数字已经是整数,则返回相同的数字。
语法
math.floor(x)
参数
x(必需) - 要向下取整的数字
步骤
下面是执行所需任务的算法/步骤:
- 使用import关键字导入math模块。
-
创建一个函数 GreatestInteger() ,它通过将数字作为参数来返回数字的最大整数函数值。
-
使用math模块的 floor() 函数(取数字的下界),然后使用 int() 函数(将给定对象转换为整数,返回数字的最大整数函数),将其转换为整数,并使用return语句返回它。
-
创建一个变量来存储输入的数字。
-
通过将输入的数字作为参数调用 GreatestInteger() 函数,并打印其返回的最大整数函数值。
示例
以下程序使用math.floor()函数返回数字的最大整数函数值:
# importing a math module
import math
# creating a function that calculates the
# greatest integer function value of a number passed
def GreatestInteger(num):
# getting the floor of a number and converting to an integer
# which is the greatest integer function of a number
return int(math.floor(num))
# inpur number
inputNumber = 3.4
# calling the GreatestInteger() function by passing input
# number as an argument
print('The Greatest Integer Less than',inputNumber,'is:',GreatestInteger(inputNumber))
输出
执行上述程序后,将会生成以下输出:
The Greatest Integer Less than 3.4 is: 3
最大整数函数使用int()函数
步骤
以下是执行所需任务的算法/步骤 –
- 检查传入的数字是否大于0,如果是,则使用 int() 函数返回传递的数字的整数格式(从给定对象返回整数)。这将返回小于给定参数的最大数字。
-
否则返回数字-1的整数格式。
-
通过传递一个数字作为参数来调用GreatestInteger()函数,并打印它返回的数字的最大整数函数值。
-
类似地,查找其他数字并观察变化。
示例
以下程序使用int()函数返回一个数字的最大整数函数值-
# creating a function that returns by taking the given number
# as an argument
def GreatestInteger(n):
# Checking if the number is greater than 0
if(n>=0):
# Return the integer format of the given number
return int(n)
# Else if it is a negative number
# Return the integer format -1
return int(n) -1
# calling the GreatestInteger() function by passing given number as an argument
print('The Greatest Integer Less than 5.2 is:',GreatestInteger(5.2))
print('The Greatest Integer Less than 0.2 is:',GreatestInteger(0.2))
# Negative Number
print('The Greatest Integer Less than 0.2 is:',GreatestInteger(-0.2))
输出
执行以上程序后,将生成以下输出结果 –
The Greatest Integer Less than 5.2 is: 5
The Greatest Integer Less than 0.2 is: 0
The Greatest Integer Less than 0.2 is: None
结论
在本文中,我们学习了两种不同的Python方法来计算小于x的最大整数。我们还学习了如何使用int()函数将给定的数字转换为整数。在本文中,我们深入了解了最大整数函数。我们还学习了floor()函数,用于计算相同的内容。