用Python实现常见数学函数
发布时间:2023-07-02 05:22:43
Python是一种功能强大的编程语言,拥有丰富的库和模块,可以方便地实现常见的数学函数。下面是使用Python实现一些常见数学函数的示例代码。
1. 求平方根:
import math
def square_root(x):
return math.sqrt(x)
print(square_root(16)) # 输出:4.0
2. 求绝对值:
def absolute_value(x):
if x < 0:
return -x
else:
return x
print(absolute_value(-5)) # 输出:5
3. 求幂运算:
def power(base, exponent):
return base ** exponent
print(power(2, 3)) # 输出:8
4. 求对数:
def logarithm(x, base):
return math.log(x, base)
print(logarithm(10, 2)) # 输出:3.3219280948873626
5. 求三角函数:
def sine(angle):
return math.sin(angle)
print(sine(math.pi/2)) # 输出:1.0
6. 求阶乘:
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
print(factorial(5)) # 输出:120
7. 求最大公约数:
def gcd(a, b):
while b != 0:
a, b = b, a % b
return a
print(gcd(12, 18)) # 输出:6
这些只是一部分常见数学函数的示例代码,Python还有更多的数学函数可以使用。通过使用Python所提供的数学库和自定义函数,可以方便地实现各种数学计算和运算。
