Python的函数math模块提供了一系列数学运算相关的函数(shu),这些函数对于(yu)科学计算、调用数据分析以及需要在(zai)Python程序中执行(xing)复杂数学运算的函数任何场景都非常有用,以(yi)下是调用一些常(chang)用的(de)math模块函数及其用法:(图片来源网络,侵删)
1、函数math.sqrt(x): 返回x的调用平方(fang)根。

2、函数math.fabs(x): 返回x的调用绝对值。

3、函数math.factorial(x): 返回x的调用(yong)阶乘。

4、函数math.pow(x,调用 y): 返回x的y次幂。
5、函数math.log(x[,调用 base]): 返回x的自然对数,base参数可选,函数默认为e。
6、math.log10(x): 返回以10为底的x的对(dui)数。
7、math.exp(x): 返回(hui)e的x次幂。
8、math.sin(x): 返回x的正弦值(在弧度中)。
9、math.cos(x): 返回x的余弦值(在弧度中)。
10、math.tan(x): 返回x的(de)正(zheng)切(qie)值。
11、math.pi: 返回π的(de)值。
12、math.e: 返回自然对数(shu)的底数e的值。
13、math.trunc(x): 返回x的整数部分。
14、math.ceil(x): 返回大于或等于x的最小整数。
15、math.floor(x): 返回小于(yu)或等于x的最(zui)大整数(shu)。
16、math.modf(x): 将x分解为小数和整数部分(fen)。
接下来,我们将通过一些示例来展示(shi)如(ru)何使用math模块中的(de)函数:
import math计算(suan)平方(fang)根square_root = math.sqrt(16)print("Square root of 16 is", square_root)计算绝对(dui)值absolute_value = math.fabs(5.3)print("Absolute value of 5.3 is", absolute_value)计算阶乘factorial = math.factorial(5)print("Factorial of 5 is", factorial)幂运算power = math.pow(2, 3)print("2 raised to the power of 3 is", power)自(zi)然对数natural_log = math.log(10)print("Natural logarithm of 10 is", natural_log)以10为底的对数log10 = math.log10(100)print("Logarithm base 10 of 100 is", log10)e的(de)幂e_power = math.exp(1)print("e raised to the power of 1 is", e_power)三角函数angle_in_radians = math.pi / 4sine_value = math.sin(angle_in_radians)cosine_value = math.cos(angle_in_radians)print("Sine of pi/4 is", sine_value)print("Cosine of pi/4 is", cosine_value)圆周率π和(he)自然对数底数epi = math.pie = math.eprint("Value of Pi is", pi)print("Value of E is", e)取整相(xiang)关函数integer_part = math.trunc(3.14159)ceiling_value = math.ceil(3.14159)floor_value = math.floor(3.14159)print("Truncated value of 3.14159 is", integer_part)print("Ceiling value of 3.14159 is", ceiling_value)print("Floor value of 3.14159 is", floor_value)上述代码展示了如何利(li)用math模块进(jin)行常见的数学运算,在使用math模块时,需要先导入该模块,然后才能调(diao)用(yong)其提供的函数,三角函数如sin, cos, tan等都需要接受弧度作为参数,而不是度数(shu),如果需要将(jiang)度数转(zhuan)换为弧度,可以使用math.radians(degrees)函数,反之,将弧度转换为度数,则可以使用(yong)math.degrees(radians)函数(shu)。
电话:18123279828
网 址:http://bindebake.cn/
邮 箱:97675878@qq.com
地 址:上海市宝山66号