Python中的數學常量


在本文中,我們將學習 Python 的數學常量以及如何使用它們。

math 模組包含一些定義的常量,可用於各種數學運算。這些數學常量返回的值與其標準定義值相同。

以下是在 Python 程式語言中可用的 math 模組常量

  • Python math.e 常量

  • Python math.pi 常量

  • Python math.tau 常量

  • Python math.inf 常量

  • Python math.nan 常量

Python math.e 常量

math.e 常量返回尤拉數,即 **2.71828182846**。

語法

math.e

**返回值** - 它返回浮點數 2.71828182846,表示數學常數 e。

示例

演算法(步驟)

以下是執行所需任務的演算法/步驟:

  • 使用 import 關鍵字匯入 **math** 模組。

  • 使用 math 模組的 e 常量和 (.) 運算子列印尤拉值 **e**。

示例

以下程式使用 Python 中的 math 模組返回 math.e 常量的值:

# importing math module import math # printing the Euler value e print ("The Euler value e = ", math.e)

輸出

執行上述程式後,將生成以下輸出:

The Euler value e = 2.718281828459045

Python math.pi 常量

math.pi 常量返回 pi 值,即 3.14159265359。它被定義為圓的周長與其直徑的比率。

語法

math.pi

**返回值** - 它返回浮點數 **3.14159265359**,表示數學常數 PI。

示例

演算法(步驟)

以下是執行所需任務的演算法/步驟:

  • 使用 import 關鍵字匯入 **math** 模組。

  • 使用 math 模組的 pi 常量和 (.) 運算子列印 **pi** 值。

示例

以下程式使用 Python 中的 math 模組返回 math.pi 常量的值:

# importing math module import math # printing the pi value print ("The pi value = ", math.pi)

輸出

執行上述程式後,將生成以下輸出:

The pi value = 3.141592653589793

Python math.tau 常量

math.tau 常量返回 **tau** 值 **6.283185307179586**。它被定義為圓的周長與其半徑的比率。

語法

math.tau

**返回值** - 它返回浮點數 6.283185307179586,表示數學常數 **tau**。

示例

演算法(步驟)

以下是執行所需任務的演算法/步驟:

  • 使用 import 關鍵字匯入 **math** 模組。

  • 使用 math 模組的 **tau** 常量和 (.) 運算子列印 **tau** 值。

示例

以下程式使用 Python 中的 math 模組返回 math. tau 常量的值:

# importing math module import math # printing the tau value print ("The tau value = ", math.tau)

輸出

執行上述程式後,將生成以下輸出:

The tau value = 6.283185307179586

Python math.inf 常量

math.inf 常量返回正無窮大的值。對於負無窮大,使用 -math.inf。

inf 常量與 float("inf") 相同。

語法

math.inf

**返回值**: 它返回表示 **正無窮大** 值的浮點數。

示例

演算法(步驟)

以下是執行所需任務的演算法/步驟:

  • 使用 import 關鍵字匯入 **math** 模組。

  • 使用 math 模組的 inf 常量和 (.) 運算子列印正無窮大的值。

  • 使用 math 模組的 inf 常量和 (.) 運算子列印負無窮大的值,並應用 **-(負號)**。

示例

以下程式使用 Python 中的 math 模組返回 math.inf 常量的值:

# importing math module import math # printing the value of positive infinity print ("The value of positive infinity = ", math.inf) # printing the value of negative infinity print ("The value of negative infinity = ", -math.inf)

輸出

執行上述程式後,將生成以下輸出:

The value of positive infinity = inf
The value of negative infinity = -inf

Python math.nan 常量

math.nan 常量返回浮點 **nan**(非數字)值。這不是一個有效的數字。float("nan") 與 nan 常量類似。

語法

math.nan

**返回值**: 它返回浮點數 **nan**(非數字)。

示例

演算法(步驟)

以下是執行所需任務的演算法/步驟:

  • 使用 import 關鍵字匯入 **math** 模組。

  • 使用 math 模組的 nan 常量和 (.) 運算子列印 nan 值。

示例

以下程式使用 Python 中的 math 模組返回 math.nan 常量的值:

# importing math module import math # printing the nan value print ("The nan value = ", math.nan)

輸出

執行上述程式後,將生成以下輸出:

The nan value = nan

結論

在本文中,我們學習了 Python 中可用的數學常量。我們還透過一些示例演示瞭如何在 Python 程式中使用這些常量。

更新於: 2022年10月25日

978 次檢視

啟動你的 職業生涯

透過完成課程獲得認證

開始
廣告

© . All rights reserved.