Python math.pi 常量



Python 的math.pi常量用於表示數學常數Π(pi),其近似值為 3.14159。它是在 Python 的math 模組中提供的預定義值,通常用於涉及圓形、球體、三角函式和其他幾何計算的數學計算。

在數學上,Π是一個特殊的數字,表示圓的周長與其直徑之比。無論圓的大小如何,如果將圓的周長除以其直徑,您始終會得到Π。它是一個無理數,這意味著它不能表示為簡單的分數,並且它的十進位制表示無限地持續下去而不會重複。

語法

以下是 Python 的math.pi常量的基本語法:

math.pi

返回值

該常量返回 PI 的值。

示例 1

在下面的示例中,我們使用 math.pi 常量來計算給定半徑的圓的面積:

import math
radius = 5
area = math.pi * (radius ** 2)
print("The area of the circle with radius", radius, "is:", area)

輸出

以下是上述程式碼的輸出:

The area of the circle with radius 5 is: 78.53981633974483

示例 2

在這裡,我們計算給定半徑的圓的周長:

import math
radius = 8
circumference = 2 * math.pi * radius
print("The circumference of the circle with radius", radius, "is:", circumference)

輸出

獲得的輸出如下:

The circumference of the circle with radius 8 is: 50.26548245743669

示例 3

在此示例中,我們計算給定半徑的球體的體積:

import math
radius = 4
volume = (4/3) * math.pi * (radius ** 3)
print("The volume of the sphere with radius", radius, "is:", volume)

輸出

產生的結果如下:

The volume of the sphere with radius 4 is: 268.082573106329

示例 4

現在,我們透過提供圓的半徑和弧的中心角(以度為單位)來計算弧的長度。我們使用弧長公式,即半徑乘以中心角(以弧度為單位)(r * θ)。然後,在執行計算之前,我們使用math.radians() 方法將角度從度轉換為弧度:

import math
radius = 10
angle_in_degrees = 45
angle_in_radians = math.radians(angle_in_degrees)
arc_length = radius * angle_in_radians
print("The length of the arc with radius", radius, "and angle", angle_in_degrees, "degrees is:", arc_length)

輸出

我們得到如下所示的輸出:

The length of the arc with radius 10 and angle 45 degrees is: 7.853981633974483
python_maths.htm
廣告