如何在Python中不使用math模組的情況下進行平方根運算?
在本文中,我們將向您展示如何在不使用math模組的情況下在Python中執行平方根運算。以下是完成此任務的各種方法
- 使用指數運算子 **
- 使用數學邏輯
使用指數運算子 **
在不使用math模組的情況下,在Python中查詢數字平方根最簡單的方法是使用內建的指數運算子 **(它是指數運算子,因為它計算第一個運算元的第二個運算元次方)。
演算法(步驟)
以下是執行所需任務的演算法/步驟:
建立一個變數來儲存輸入數字。
使用指數運算子 (**) 獲取數字的平方根。
列印輸入數字的平方根。
示例
以下程式返回輸入數字的平方根,不使用math模組,並使用** 運算子:
# input number inputNumber = 25 # getting the square root of a number using the exponential operator** squareRoot = inputNumber**(1/2) # printing the square root of a number print("The square root of", inputNumber, "=", squareRoot)
輸出
執行上述程式將生成以下輸出:
('The square root of', 25, '=', 1)
在這個方法中,我們取一個數字,並使用 ** 運算子計算其平方根,將指數值傳遞為 (1/2) 或 0.5,然後列印結果。
使用數學邏輯
此方法類似於二分查詢。
演算法(步驟)
以下是執行所需任務的演算法/步驟:
建立一個變數來儲存輸入數字。
將最小值初始化為 0。
將最大值初始化為輸入數字。
使用for迴圈重複迴圈 10 次。
透過將最小值和最大值相加除以 2(獲取最小值和最大值的平均值)來獲取最小值和最大值的中間值。
使用** 運算子計算中間值的平方,並將其儲存在一個變數中。
使用if條件語句檢查中間值的平方值是否等於輸入數字,如果為真,則使用break語句中斷程式碼(Python中的break語句終止當前迴圈,並在下一條語句處恢復執行,就像C語言中的傳統break一樣)。
否則,檢查中間值的平方值是否大於輸入數字,如果為真,則將最大值設定為中間值。
否則,如果中間值的平方值小於數字,則將最小值設定為中間值。
列印中間值,即輸入數字的結果平方根。
示例
以下程式返回輸入數字的平方根,不使用math模組,並使用數學邏輯:
# input number number = 9 # initializing minimum value as 0 minimum = 0 # initializing maximum value with input number maximum =number # repeating the loop 10 times using for loop for i in range(10): # getting the middle value middle =(minimum+maximum)/2 # getting the square of the middle value squareValue=middle**2 # checking whether the square value of the middle value is equal to the number if squareValue ==number: # break the code if the condition is true break # checking whether the square value of the middle value is more than the number # taking max value as the middle value if the condition is true maximum=middle # else if the square value of the middle value is less than the number # taking the min value as a middle minimum=middle # printing the middle value which is the resultant square root print("The resultant square root of", number, "=", middle)
輸出
執行上述程式將生成以下輸出:
('The resultant square root of', 9, '=', 4)
結論
在本文中,我們學習了兩種不同的方法來計算給定數字的平方根,而無需使用math模組。我們還學習瞭如何使用指數運算子(**)計算平方或平方根。我們還使用類似於二分查詢的數學邏輯方法計算了平方。
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP