Python学习 -- Math模块和Random模块

math 模块提供了许多数学函数,用于执行各种数学运算。以下是一些常用的 math 函数以及相应的示例代码:

math.sqrt(x): 计算平方根。

import math
x = 25
square_root = math.sqrt(x)
print(f"√{x} = {square_root}")

math.pow(x, y): 计算 x 的 y 次方。

import math
x = 2
y = 3
result = math.pow(x, y)
print(f"{x}^{y} = {result}")

math.sin(x) 和 math.cos(x): 计算给定角度 x(弧度)的正弦和余弦值。

import math
angle_degrees = 45
angle_radians = math.radians(angle_degrees)
sin_value = math.sin(angle_radians)
cos_value = math.cos(angle_radians)
print(f"sin({angle_degrees}°) = {sin_value}")
print(f"cos({angle_degrees}°) = {cos_value}")

math.exp(x): 计算指数函数 e^x 的值。

import math
x = 2
exp_result = math.exp(x)
print(f"e^{x} = {exp_result}")

math.log(x) 和 math.log10(x): 计算自然对数和以 10 为底的对数。

import math
x = 100
ln_result = math.log(x)
log10_result = math.log10(x)
print(f"ln({x}) = {ln_result}")
print(f"log10({x}) = {log10_result}")

math.ceil(x): 向上取整,返回不小于 x 的最小整数。

import math
x = 3.7
ceil_result = math.ceil(x)
print(f"向上取整({x}) = {ceil_result}")

math.floor(x): 向下取整,返回不大于 x 的最大整数。

import math
x = 3.7
floor_result = math.floor(x)
print(f"向下取整({x}) = {floor_result}")

math.fabs(x): 返回 x 的绝对值。

import math
x = -5
abs_result = math.fabs(x)
print(f"|{x}| = {abs_result}")

math.factorial(x): 计算 x 的阶乘。

import math
x = 5
factorial_result = math.factorial(x)
print(f"{x}的阶乘 = {factorial_result}")

math.modf(x): 将 x 拆分为整数部分和小数部分,返回一个元组。

import math
x = 3.14
integer_part, fractional_part = math.modf(x)
print(f"{x}的整数部分 = {integer_part}")
print(f"{x}的小数部分 = {fractional_part}")

random 模块提供了生成伪随机数的函数,用于模拟随机事件或进行随机选择。以下是一些常用的 random 模块函数以及相应的示例代码:

random.random(): 生成一个位于 [0.0, 1.0) 范围内的随机浮点数。

import random
random_float = random.random()
print(f"随机浮点数: {random_float}")

random.randint(a, b): 生成一个位于 [a, b] 范围内的随机整数。

import random
random_int = random.randint(1, 10)
print(f"随机整数: {random_int}")

random.choice(seq): 从序列 seq 中随机选择一个元素。

import random
my_list = [1, 2, 3, 4, 5]
random_choice = random.choice(my_list)
print(f"随机选择: {random_choice}")

random.shuffle(seq): 随机打乱序列 seq 中的元素顺序(原地操作)。

import random
my_list = [1, 2, 3, 4, 5]
random.shuffle(my_list)
print(f"打乱后的列表: {my_list}")

random.sample(population, k): 从总体 population 中随机选择 k 个唯一的元素。

import random
my_population = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
random_sample = random.sample(my_population, 3)
print(f"随机抽样: {random_sample}")

random.uniform(a, b): 生成一个位于 [a, b] 范围内的随机浮点数。

import random
random_float = random.uniform(1.0, 2.0)
print(f"随机浮点数: {random_float}")

你可能感兴趣的:(2023Python学习,python,学习,开发语言)