如何在 Python 中找到小於 x 的最大整數?
在本文中,我們將向您展示如何在 python 中找到小於 x 的最大整數。
最大整數函式 [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() 函式,它用於計算相同的值。