资讯动态

数字类型与math/random实战——Python计算能力全解析

发布时间:2026/10/2 15:30:33 来源:尧图企业网站定制
它不仅仅是用来处理文字的,它的数字运算能力也是同样的强大。不管是整数和浮点数, 还是科学计算, 再或者是产生随机数和进行数学函数计算, 今天在今天的讲解里会把这些内容统统讲透彻, 从而让你能够彻底掌握这个所谓的“数学大脑”。一、关于数字类型的整体全景图, 在这一点一的部分当中, 提到了总共有四种不一样的数字类型。# 整数 int没有大小限制a 42b -100c 999999999999999999999999999999 # Python整数不会溢出print(type(a)) ## 浮点数 float带小数点的数字 pi 3.141592653589793temperature -5.5scientific 1.23e4 # 科学计数法 12300.0tiny 1.23e-10 # 0.000000000123print(type(pi)) ## 复数 complexPython原生支持z 3 4j # j表示虚部不是iprint(z.real) # 实部: 3.0print(z.imag) # 虚部: 4.0print(abs(z)) # 模长: 5.0 勾股定理 √(3²4²)# 布尔值 bool其实是int的子类 print(True True) # 2 —— True1, False0print(True * 10) # 10print(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.0print(float(3.14)) # 3.14# round() → 四舍五入注意银行家舍入print(round(3.5)) # 4print(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.3print(1.1 2.2) # 3.3000000000000003# 为什么因为计算机用二进制存储浮点数0.1在二进制中是无限循环小数# 解决方案1用round()处理显示result 0.1 0.2print(round(result, 10)) # 0.3 —— 显示时四舍五入# 解决方案2用Decimal做精确计算金融场景必备from decimal import Decimal, getcontextgetcontext().prec 28 # 设置精度a Decimal(0.1)b Decimal(0.2)print(a b) # 0.3 —— 精确price Decimal(19.99)quantity Decimal(3)total price * quantityprint(f总价: {total}) # 总价: 59.97 —— 精确# 解决方案3用Fraction处理分数from Fraction import Fractionf 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 —— 绝对值返回floatprint(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.141592653589793print(math.e) # 2.718281828459045print(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 60radians math.radians(degrees) # 角度转弧度print(math.sin(radians)) # sin(60°) ≈ 0.866# 其他实用函数 print(math.factorial(5)) # 120 —— 阶乘 5! 5×4×3×2×1print(math.gcd(12, 8)) # 4 —— 最大公约数print(math.lcm(4, 6)) # 12 —— 最小倍数Python 3.9print(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 mathdef 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:breaktry:idx int(choice) - 1if not (0 idx len(operations)):print( 无效选择)continuename, 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 中的一个步长为2print(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, weightsweights, k1)[0]print(f恭喜获得{result}!)3.这是一个实战的项目, 项目名称为1: 猜数字游戏。import randomdef guess_number():猜数字游戏number random.randint(1, 100)attempts 0max_attempts 7print(\n 猜数字游戏 (1-100))print(f你有{max_attempts}次机会\n)while attempts max_attempts:try:guess int(input(f第{attempts 1}次猜: ))attempts 1if guess number:print( 太小了)elif guess number:print( 太大了)else:print(f 恭喜你用了{attempts}次猜中了答案是{number})returnexcept ValueError:print( 请输入整数)print(f 游戏结束正确答案是{number})guess_number()3.这是第三个在现实中用来练习的项目, 具体名字叫做随机密码生成器。import randomimport stringdef generate_password(length16, use_symbolsTrue):生成安全的随机密码Args:length: 密码长度建议至少12位use_symbols: 是否包含特殊字符# 字符池letters string.ascii_letters # abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZdigits string.digits # 0123456789symbols !#$%^*()_-[]{}|;:,.?# 确保每种字符至少出现一次password [random.choice(string.ascii_lowercase),random.choice(string.ascii_uppercase),random.choice(digits),]if use_symbols:password.append(random.choice(symbols))# 填充剩余长度pool letters digitsif use_symbols:pool symbolsremaining length - len(password)password.extend(random.choices(pool, kremaining))# 打乱顺序random.shuffle(password)return .join(password)# 批量生成print( 随机密码生成器)for i in range(5):pwd generate_password(length16)strength 强 if len(pwd) 12 else 弱print(f 密码{i1}: {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_symbolsFalse)})3.这是第四个实际的项目, 第三个项目的内容是关于模拟数据的生成了。import randomfrom datetime import datetime, timedeltadef generate_mock_users(count10):生成模拟用户数据用于测试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-65age random.randint(18, 65)# 随机城市city random.choice(cities)# 随机注册日期2024年内reg_date base_date timedelta(daysrandom.randint(0, 364))# 随机余额正态分布均值5000标准差2000balance 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 statisticsdata [23, 45, 67, 32, 89, 54, 21, 76, 43, 58]# 集中趋势 print(statistics.mean(data)) # 平均值: 50.8print(statistics.median(data)) # 中位数: 49.5print(statistics.mode([1,2,2,3])) # 众数: 2# 离散程度 print(stdev : statistics.stdev(data)) # 标准差: ≈22.0print(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 █ * countprint(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.97tax subtotal * tax_rate # 11.6961total 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 5amount principal * (Decimal(1) rate) ** yearsprint(f{years}年后本息合计: ¥{amount.quantize(Decimal(0.01))})# 5年后本息合计: ¥118768.63# 场景避免浮点累加误差 # 用float累加float_sum sum([0.1] * 10)print(ffloat累加: {float_sum}) # 0.9999999999999999 ← 有误差# 用Decimal累加dec_sum sum([Decimal(0.1)] * 10)print(fDecimal累加: {dec_sum}) # 1.0 ← 精确六、这是针对现实彩票号码进行模拟的一个综合性的实践应用。把这个元素同其他事物给结合起来, 然后去搞出一个那个让人觉得非常有趣的项目。import randomfrom collections import Counterdef lottery_simulator(draws100):双色球模拟器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] 1blue_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-5i}期: {red_str} {blue:02d})# 红球热号TOP6print(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 * 100bar █ * int(pct / 2)print(f {rank}. 号码 {num:02d}: 出现{count}次 ({pct:.1f}%) {bar})# 蓝球热号TOP5print(f\n 蓝球出现频率 TOP5:)print(- * 30)top_blue blue_counts.most_common(5)for rank, (num, count) in enumerate(top_blue, 1):pct count / draws * 100bar █ * 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(draws1000)运行效果双色球模拟器模拟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**yx^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模块提供了完整的数学函数库。下一步就是打算使用一下这些掌握的知识, 去尝试制作一个属于你自己的小型工具产品, 你完全可以考虑开发如房贷计算功能或者随机抽奖程序或者是数据分析脚本等方面的工作。如果你认为这个内容对你有用, 请点击点赞按钮并点击收藏标签。在下一期的节目里, 我们将深入讲解关于切片步长逆序这一概念以及它是如何作为序列操作的降维打击来发挥作用的。

读完文章,也想定制专属网站?

尧图设计师 24 小时内与您沟通定制方案

免费获取报价 →
↑