☰
数字类型与math/random实战——Python计算能力全解析
2026/10/2 15:30:27 网站建设 项目流程

它不仅仅是用来处理文字的,它的数字运算能力也是同样的强大。不管是整数和浮点数, 还是科学计算, 再或者是产生随机数和进行数学函数计算, 今天在今天的讲解里会把这些内容统统讲透彻, 从而让你能够彻底掌握这个所谓的“数学大脑”。

一、关于数字类型的整体全景图, 在这一点一的部分当中, 提到了总共有四种不一样的数字类型。

# ===== 整数 int:没有大小限制!=====

a = 42

b = -100

c = 999999999999999999999999999999 # Python整数不会溢出!

print(type(a)) #

# ===== 浮点数 float:带小数点的数字 =====

pi = 3.141592653589793

temperature = -5.5

scientific = 1.23e4 # 科学计数法 = 12300.0

tiny = 1.23e-10 # = 0.000000000123

print(type(pi)) #

# ===== 复数 complex:Python原生支持!

=====

z = 3 + 4j # j表示虚部(不是i)

print(z.real) # 实部: 3.0

print(z.imag) # 虚部: 4.0

print(abs(z)) # 模长: 5.0 (勾股定理 √(3²+4²))

# ===== 布尔值 bool:其实是int的子类 =====

print(True + True) # 2 —— True=1, False=0

print(True * 10) # 10

print(isinstance(True, int)) # True —— bool是int的子类

1.第二部分是关于类型转换, 这种类型转换具体指的是数字之间相互进行的变化操作。

# int() → 转整数(截断小数,不四舍五入)

print(int(3.9)) # 3 —— 直接截断

print(int("42")) # 42 —— 字符串转整数

print(int("101", 2)) # 5 —— 二进制字符串转整数

# float() → 转浮点数

print(float(3)) # 3.0

print(float("3.14")) # 3.14

# round() → 四舍五入(注意银行家舍入)

print(round(3.5)) # 4

print(round(2.5)) # 2 —— 银行家舍入:到最近的偶数

print(round(3.14159, 2)) # 3.14 —— 指定保留位数

# divmod() → 同时获取商和余数

quotient, remainder = divmod(17, 5)

print(f"商={quotient}, 余数={remainder}") # 商=3, 余数=2

# pow() → 幂运算(支持模运算)

print(pow(2, 10)) # 1024 —— 2的10次方

print(pow(2, 10, 1000)) # 24 —— (2^10) % 1000,比 ** % 更高效

1.3 ️ 浮点数的精度陷阱

# 浮点数精度问题

print(0.1 + 0.2) # 0.30000000000000004 —— 不是精确的0.3!

print(1.1 + 2.2) # 3.3000000000000003

# 为什么?

因为计算机用二进制存储浮点数,0.1在二进制中是无限循环小数

# 解决方案1:用round()处理显示

result = 0.1 + 0.2

print(round(result, 10)) # 0.3 —— 显示时四舍五入

# 解决方案2:用Decimal做精确计算(金融场景必备)

from decimal import Decimal, getcontext

getcontext().prec = 28 # 设置精度

a = Decimal('0.1')

b = Decimal('0.2')

print(a + b) # 0.3 —— 精确!

price = Decimal('19.99')

quantity = Decimal('3')

total = price * quantity

print(f"总价: {total}") # 总价: 59.97 —— 精确!

# 解决方案3:用Fraction处理分数

from Fraction import Fraction

f = Fraction(1, 3) + Fraction(1, 6)

print(f) # 1/2 —— 精确分数

print(float(f)) # 0.5

二、math模块, 它是那种内置好的计算器功能。

math这个模块它提供了很多数学函数, 这些函数呢覆盖了大家日常编程里百分之九十九的数学需求, 也就是说在平常的工作当中几乎是用得上的。

2.对于日常中经常会用到的那些个数学函数, 这里有一点点小速查。

import math

# ===== 基本运算 =====

print(math.ceil(3.2)) # 4 —— 向上取整

print(math.floor(3.8)) # 3 —— 向下取整

print(math.fabs(-5)) # 5.0 —— 绝对值(返回float)

print(abs(-5)) # 5 —— 绝对值(返回int或原类型)

# ===== 幂与对数 =====

print(math.sqrt(16)) # 4.0 —— 平方根

print(math.pow(2, 10)) # 1024.0 —— 幂运算

print(math.log(1024, 2)) # 10.0 —— 以2为底的对数

print(math.log(100)) # 4.605... —— 自然对数(ln)

print(math.log10(100)) # 2.0 —— 以10为底的对数

# ===== 三角函数(参数为弧度)=====

print(math.pi) # 3.141592653589793

print(math.e) # 2.718281828459045

print(math.sin(math.pi / 2)) # 1.0 —— sin(90°)

print(math.cos(0)) # 1.0 —— cos(0°)

print(math.tan(math.pi / 4)) # 1.0 —— tan(45°)

# 角度→弧度 转换

degrees = 60

radians = math.radians(degrees) # 角度转弧度

print(math.sin(radians)) # sin(60°) ≈ 0.866

# ===== 其他实用函数 =====

print(math.factorial(5)) # 120 —— 阶乘 5!

= 5×4×3×2×1

print(math.gcd(12, 8)) # 4 —— 最大公约数

print(math.lcm(4, 6)) # 12 —— 最小倍数(Python 3.9+)

print(math.comb(5, 2)) # 10 —— 组合数 C(5,2)

# ===== 特殊函数 =====

print(math.isfinite(1.0)) # True —— 是否有限数

print(math.isinf(float('inf'))) # True —— 是否无穷大

print(math.isnan(float('nan'))) # True —— 是否非数字

2.这是关于数学方面的实际操作内容, 其主题具体涉及到了一个用于计算功能的程序实例。

import math

def calculator():

"""简易科学计算器"""

print("\n Python科学计算器")

print("=" * 30)

operations = [

("加法", lambda a, b: a + b),

("减法", lambda a, b: a - b),

("乘法", lambda a, b: a * b),

("除法", lambda a, b: a / b if b !

= 0 else "错误:除数不能为零"),

("幂运算", lambda a, b: a ** b),

("开平方", lambda a, _: math.sqrt(a) if a >= 0 else "错误:负数无实数平方根"),

("对数(log10)", lambda a, _: math.log10(a) if a > 0 else "错误:必须大于0"),

("正弦(sin)", lambda a, _: math.sin(math.radians(a))),

("阶乘(!

)", lambda a, _: math.factorial(int(a)) if a == int(a) and a >= 0 else "错误:非负整数"),

]

print("可用操作:")

for idx, (name, _) in enumerate(operations, 1):

print(f" {idx}. {name}")

while True:

choice = input("\n选择操作(序号/q退出): ").strip()

if choice.lower() == 'q':

break

try:

idx = int(choice) - 1

if not (0 <= idx < len(operations)):

print(" 无效选择")

continue

name, func = operations[idx]

if idx in [6, 7]: # 单操作数

a = float(input(f"输入数值({name}): "))

result = func(a, None)

else:

a = float(input("输入第一个数: "))

b = float(input("输入第二个数: "))

result = func(a, b)

print(f"\n 结果: {result}")

except ValueError:

print(" 请输入有效数字")

except Exception as e:

print(f" 错误: {e}")

calculator()

三、模块这一块事情, 是让整个程序的运行过程当中充满不确定性的这种状况的一个存在。

它是比较有趣的模块之一, 并且从游戏开发到数据采样都都离不开它。

3.在基础层面, 随机数的生成这一过程是被讨论的。

import random

# ===== 随机整数 =====

print(random.randint(1, 100)) # 1-100之间(包含两端)

print(random.randrange(0, 10, 2)) # 0,2,4,6,8 中的一个(步长为2)

print(random.choice([1, 2, 3])) # 从列表中随机选一个

# ===== 随机浮点数 =====

print(random.random()) # 0.0 ~ 1.0 之间的随机浮点数

print(random.uniform(1.5, 10.5)) # 1.5 ~ 10.5 之间的均匀分布

# ===== 序列操作 =====

items = ['苹果', '香蕉', '橙子', '葡萄', '西瓜']

print(random.choice(items)) # 随机取一个

print(random.sample(items, 3)) # 随机取3个(不重复)

random.shuffle(items) # 原地打乱顺序

print(items)

# ===== 加权随机选择 =====

# 比如模拟抽奖:一等奖概率1%,二等奖10%,三等奖89%

prizes = [("一等奖", 1), ("二等奖", 10), ("三等奖", 89)]

population, weights = zip(*prizes)

result = random.choices(population, weights=weights, k=1)[0]

print(f"恭喜获得:{result}!

")

3.这是一个实战的项目, 项目名称为1: 猜数字游戏。

import random

def guess_number():

"""猜数字游戏"""

number = random.randint(1, 100)

attempts = 0

max_attempts = 7

print("\n 猜数字游戏 (1-100)")

print(f"你有{max_attempts}次机会\n")

while attempts < max_attempts:

try:

guess = int(input(f"第{attempts + 1}次猜: "))

attempts += 1

if guess < number:

print(" 太小了!

")

elif guess > number:

print(" 太大了!

")

else:

print(f" 恭喜你!用了{attempts}次猜中了!

答案是{number}")

return

except ValueError:

print(" 请输入整数")

print(f" 游戏结束!

正确答案是{number}")

guess_number()

3.这是第三个在现实中用来练习的项目, 具体名字叫做随机密码生成器。

import random

import string

def generate_password(length=16, use_symbols=True):

"""

生成安全的随机密码

Args:

length: 密码长度(建议至少12位)

use_symbols: 是否包含特殊字符

"""

# 字符池

letters = string.ascii_letters # abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ

digits = string.digits # 0123456789

symbols = "!

@#$%^&*()_+-=[]{}|;:,.<>?

"

# 确保每种字符至少出现一次

password = [

random.choice(string.ascii_lowercase),

random.choice(string.ascii_uppercase),

random.choice(digits),

]

if use_symbols:

password.append(random.choice(symbols))

# 填充剩余长度

pool = letters + digits

if use_symbols:

pool += symbols

remaining = length - len(password)

password.extend(random.choices(pool, k=remaining))

# 打乱顺序

random.shuffle(password)

return ''.join(password)

# 批量生成

print(" 随机密码生成器")

for i in range(5):

pwd = generate_password(length=16)

strength = "强" if len(pwd) >= 12 else "弱"

print(f" 密码{i+1}: {pwd} [{strength}]")

# 不同场景的推荐长度

print("\n 推荐配置:")

print(f" 社交账号: {generate_password(12)}")

print(f" 邮箱密码: {generate_password(16)}")

print(f" 服务器密码: {generate_password(20)}")

print(f" 纯字母数字: {generate_password(16, use_symbols=False)}")

3.这是第四个实际的项目, 第三个项目的内容是关于模拟数据的生成了。

import random

from datetime import datetime, timedelta

def generate_mock_users(count=10):

"""生成模拟用户数据(用于测试)"""

first_names = ["张", "王", "李", "刘", "陈", "杨", "赵", "黄", "周", "吴"]

last_names = ["伟", "芳", "娜", "敏", "静", "强", "磊", "洋", "艳", "勇"]

cities = ["北京", "上海", "广州", "深圳", "杭州", "成都", "武汉", "西安"]

users = []

base_date = datetime(2024, 1, 1)

for i in range(count):

name = random.choice(first_names) + random.choice(last_names)

# 随机年龄18-65

age = random.randint(18, 65)

# 随机城市

city = random.choice(cities)

# 随机注册日期(2024年内)

reg_date = base_date + timedelta(days=random.randint(0, 364))

# 随机余额(正态分布,均值5000,标准差2000)

balance = max(0, round(random.gauss(5000, 2000), 2))

# 随机VIP等级(加权:普通70% VIP20% SVIP10%)

vip_level = random.choices(

["普通", "VIP", "SVIP"],

weights=[70, 20, 10]

)[0]

users.append({

"id": i + 1,

"name": name,

"age": age,

"city": city,

"reg_date": reg_date.strftime("%Y-%m-%d"),

"balance": balance,

"vip_level": vip_level

})

return users

# 生成并展示

users = generate_mock_users(10)

print(f"{'ID':<4} {'姓名':<6} {'年龄':<4} {'城市':<6} {'注册日期':<12} {'余额':>10} {'等级':<6}")

print("-" * 60)

for u in users:

print(f"{u['id']:<4} {u['name']:<6} {u['age']:<4} {u['city']:<6} "

f"{u['reg_date']:<12} ¥{u['balance']:>9.2f} {u['vip_level']:<6}")

四、这个部分叫做模块, 具体来说, 它是关于如何进行统计分析的入门教程。

3.4加, 这个产品里头内置了一个统计模块, 而这个统计模块就是用来做数据分析的基础工具。

import statistics

data = [23, 45, 67, 32, 89, 54, 21, 76, 43, 58]

# ===== 集中趋势 =====

print(statistics.mean(data)) # 平均值: 50.8

print(statistics.median(data)) # 中位数: 49.5

print(statistics.mode([1,2,2,3])) # 众数: 2

# ===== 离散程度 =====

print(stdev := statistics.stdev(data)) # 标准差: ≈22.0

print(statistics.variance(data)) # 方差

# ===== 实战:成绩分析 =====

scores = [85, 92, 78, 95, 88, 76, 90, 82, 96, 89, 73, 87]

print(f"\n 成绩分析报告")

print(f"{'='*30}")

print(f"人数: {len(scores)}")

print(f"平均分: {statistics.mean(scores):.1f}")

print(f"最高分: {max(scores)}")

print(f"最低分: {min(scores)}")

print(f"中位数: {statistics.median(scores):.1f}")

print(f"标准差: {statistics.stdev(scores):.1f}")

print(f"及格率: {sum(1 for s in scores if s >= 60)/len(scores)*100:.0f}%")

print(f"优秀率(≥90): {sum(1 for s in scores if s >= 90)/len(scores)*100:.0f}%")

# 分数段统计

ranges = [(90, 100, "优秀"), (80, 89, "良好"), (60, 79, "及格"), (0, 59, "不及格")]

for low, high, label in ranges:

count = sum(1 for s in scores if low <= s <= high)

bar = "█" * count

print(f" {label} ({low}-{high}): {count}人 {bar}")

五、该模块是用于金融计算的一个guard。

在前面, 我们曾经提到过这里面的情况, 因此现在我们决定展开来对它进行非常详细的说明。

from decimal import Decimal, getcontext

# ===== 场景:电商价格计算 =====

getcontext().prec = 10 # 设置全局精度

# 商品单价和数量

unit_price = Decimal('29.99')

quantity = Decimal('3')

tax_rate = Decimal('0.13') # 13%税率

# 计算

subtotal = unit_price * quantity # 89.97

tax = subtotal * tax_rate # 11.6961

total = subtotal + tax # 101.6661

# 四舍五分到分(2位小数)

final_total = total.quantize(Decimal('0.01'))

print(f"商品总价: ¥{final_total}") # ¥101.67

# ===== 场景:利率计算 =====

principal = Decimal('100000') # 本金10万

rate = Decimal('0.035') # 年利率3.5%

years = 5

amount = principal * (Decimal('1') + rate) ** years

print(f"{years}年后本息合计: ¥{amount.quantize(Decimal('0.01'))}")

# 5年后本息合计: ¥118768.63

# ===== 场景:避免浮点累加误差 =====

# 用float累加

float_sum = sum([0.1] * 10)

print(f"float累加: {float_sum}") # 0.9999999999999999 ← 有误差!

# 用Decimal累加

dec_sum = sum([Decimal('0.1')] * 10)

print(f"Decimal累加: {dec_sum}") # 1.0 ← 精确!

六、这是针对现实彩票号码进行模拟的一个综合性的实践应用。

把这个元素同其他事物给结合起来, 然后去搞出一个那个让人觉得非常有趣的项目。

import random

from collections import Counter

def lottery_simulator(draws=100):

"""双色球模拟器"""

print("\n 双色球模拟器")

print("=" * 40)

print(f"模拟{draws}次开奖,分析号码频率\n")

red_counts = Counter() # 红球(1-33)频率统计

blue_counts = Counter() # 蓝球(1-16)频率统计

results = []

for i in range(draws):

# 红球:1-33选6个不重复

red_balls = sorted(random.sample(range(1, 34), 6))

# 蓝球:1-16选1个

blue_ball = random.randint(1, 16)

results.append((red_balls, blue_ball))

# 统计频率

for ball in red_balls:

red_counts[ball] += 1

blue_counts[blue_ball] += 1

# 展示最近5期

print(" 最近5期开奖结果:")

print("-" * 40)

for i, (reds, blue) in enumerate(results[-5:], 1):

red_str = " ".join(f"{b:02d}" for b in reds)

print(f" 第{draws-5+i}期: {red_str} {blue:02d}")

# 红球热号TOP6

print(f"\n 红球出现频率 TOP6 ({draws}次开奖中):")

print("-" * 35)

top_red = red_counts.most_common(6)

for rank, (num, count) in enumerate(top_red, 1):

pct = count / draws * 100

bar = "█" * int(pct / 2)

print(f" {rank}. 号码 {num:02d}: 出现{count}次 ({pct:.1f}%) {bar}")

# 蓝球热号TOP5

print(f"\n 蓝球出现频率 TOP5:")

print("-" * 30)

top_blue = blue_counts.most_common(5)

for rank, (num, count) in enumerate(top_blue, 1):

pct = count / draws * 100

bar = "█" * int(pct / 4)

print(f" {rank}. 号码 {num:02d}: 出现{count}次 ({pct:.1f}%) {bar}")

# 理论值对比

print(f"\n 理论 vs 实际:")

expected_red = draws * 6 / 33 # 每个红球理论出现次数

expected_blue = draws / 16 # 每个蓝球理论出现次数

print(f" 红球理论每号出现: {expected_red:.1f}次")

print(f" 蓝球理论每号出现: {expected_blue:.1f}次")

print(f"\n️ 提示:这是纯随机模拟,实际彩票无规律可循,请理性购彩!

")

# 运行

lottery_simulator(draws=1000)

运行效果:

双色球模拟器

========================================

模拟1000次开奖,分析号码频率

最近5期开奖结果:

----------------------------------------

第996期: 03 11 15 22 28 31 09

第997期: 05 09 17 24 27 33 14

...

红球出现频率 TOP6 (1000次开奖中):

-----------------------------------

1. 号码 07: 出现188次 (18.8%) ████████████████████

2. 号码 22: 出现185次 (18.5%) █████████████████████

...

️ 提示:这是纯随机模拟,实际彩票无规律可循,请理性购彩!

七、速查表

需求

代码

说明

向上/下取整

math.ceil(x)/math.floor(x)

取整

平方根

math.sqrt(x)

√x

幂运算

pow(x, y)或x**y

x^y

对数

调用函数math.log, 然后传递参数x以及底数base。

任意底对数

阶乘

math是数学的意思。

n!

最大公约数

math.gcd(a, b)

GCD

随机整数

.(a, b)

含两端

随机浮点数

.()

0~1

随机选择

.(seq)

从列表之中, 随机的去取得那一个单独的项。

打乱列表

这是一个列表标记。

原地打乱

加权随机

弹出那个对象, 并且。

按权重选

固定种子

.seed(42)

这个随机数据生成操作是可以被复现和重复进行的。

精确小数

('0.1')

金融计算必用

统计平均值

对数据进行均值计算。

平均值

标准差

.stdev(data)

数据离散程度

总结一下, 它的数字运算能力远超大多数人的想象。具体来说就是int类型没有上限。它能解决精度问题。它还能让程序生动起来。math模块提供了完整的数学函数库。

下一步就是打算使用一下这些掌握的知识, 去尝试制作一个属于你自己的小型工具产品, 你完全可以考虑开发如房贷计算功能或者随机抽奖程序或者是数据分析脚本等方面的工作。

如果你认为这个内容对你有用, 请点击点赞按钮并点击收藏标签。在下一期的节目里, 我们将深入讲解关于切片步长逆序这一概念以及它是如何作为序列操作的降维打击来发挥作用的。

需要专业的网站建设服务?

联系我们获取免费的网站建设咨询和方案报价,让我们帮助您实现业务目标

立即咨询