Python数学运算—从基础到科学计算


包含编程资料、学习路线图、源代码、软件安装包等!【[点击这里]】!

一、Python数学运算:你的“数字超能力”

无论是简单的加减乘除,还是复杂的科学计算,Python都能轻松驾驭。从基础运算符到numpy的高性能数组,从符号计算到微积分求解,本文将带你解锁Python的数学超能力,让数据处理、算法实现和科学建模效率提升10倍!

在这里插入图片描述

二、基础数学运算:四则与进阶

1. 基本运算符
# 加减乘除  
print(5 + 3)    # 8  
print(10 - 2.5)  # 7.5  
print(4 * 6)     # 24  
print(9 / 3)     # 3.0(结果为浮点数)  

# 幂运算  
print(2 ** 10)  # 1024  

# 整除与取余  
print(7 // 2)   # 3  
print(7 % 2)    # 1  
2. 运算符优先级
  • 优先级从高到低:() → ** → * / // % → + -
print(3 + 4 * 2 ** 2)  # 3 + (4*(2^2)) = 19  

三、数学模块:math与cmath

1. math模块常用函数
import math  

print(math.sqrt(25))       # 5.0  
print(math.sin(math.pi/2)) # 1.0  
print(math.log(100, 10))  # 2.0  
print(math.factorial(5))  # 120  

# 常数  
print(math.pi)   # 3.141592653589793  
print(math.e)    # 2.718281828459045  
2. cmath处理复数
import cmath  

z = complex(3, 4)  
print(cmath.phase(z))          # 0.927295(弧度)  
print(cmath.polar(z))           # (5.0, 0.927295

四、科学计算三剑客:NumPy、SciPy、SymPy

1. NumPy:高性能数组运算
import numpy as np  

# 矩阵乘法  
A = np.array([[1, 2], [3, 4]])  
B = np.array([[5, 6], [7, 8]])  
print(A @ B)  # [[19 22], [43 50]]  

# 统计计算  
data = np.random.randn(1000)  
print(f"均值:{
      
      np.mean(data):.2f},标准差:{
      
      np.std(data):.2f}") 
2. SciPy:高级数学工具
from scipy.optimize import root  

# 解方程 x + cos(x) = 0  
def equation(x):  
    return x + np.cos(x)  
solution = root(equation, 0)  
print(solution.x[0])  # -0.739085  
3. SymPy:符号计算
from sympy import symbols, expand, diff  

x, y = symbols('x y')  
expr = (x + y)**3  
print(expand(expr))        # x³ + 3x²y + 3xy² + y³  
print(diff(expr, x))       # 3(x + y)²  

五、实战案例:数学问题的代码解法

1. 质数判断
def is_prime(n):  
    if n <= 1:  
        return False  
    for i in range(2, int(math.sqrt(n)) + 1):  
        if n % i == 0:  
            return False  
    return True  

print(is_prime(7919))  # True(7919是第1000个质数)  
2. 解二次方程
def solve_quadratic(a, b, c):  
    discriminant = b**2 - 4*a*c  
    if discriminant < 0:  
        return "无实根"  
    x1 = (-b + math.sqrt(discriminant)) / (2*a)  
    x2 = (-b - math.sqrt(discriminant)) / (2*a)  
    return (x1, x2)  

print(solve_quadratic(1, -5, 6))  # (3.0, 2.0)  
3. 数值积分(蒙特卡洛方法)
import random  

def monte_carlo_integrate(f, a, b, n=10**6):  
    total = 0  
    for _ in range(n):  
        x = random.uniform(a, b)  
        total += f(x)  
    return (b - a) * total / n  

result = monte_carlo_integrate(lambda x: x**2, 0, 1)  
print(f"∫x²dx从0到1 ≈ {
      
      result:.4f}")  # ≈0.3333  

六、避坑指南:数学运算5大陷阱

1.浮点数精度问题
print(0.1 + 0.2 == 0.3)  # False!实际为0.30000000000000004  
# 解决方案:使用Decimal模块或round函数  
2.大整数运算内存溢出
# Python原生支持大整数,但需注意性能  
print(10**1000)  # 可行,但计算耗时  
3.矩阵维度不匹配
# NumPy矩阵运算需维度一致,否则报ValueError  
4.符号计算与数值计算混淆
# SymPy符号对象需转换后参与数值计算  
5.忽略数学函数定义域
print(math.sqrt(-1))  # ValueError  
print(cmath.sqrt(-1))  # 1j(正确使用复数)  

图片

总结

  • 最后希望你编程学习上不急不躁,按照计划有条不紊推进,把任何一件事做到极致,都是不容易的,加油,努力!相信自己!

文末福利

  • 最后这里免费分享给大家一份Python全套学习资料,希望能帮到那些不满现状,想提升自己却又没有方向的朋友,也可以和我一起来学习交流呀。
包含编程资料、学习路线图、源代码、软件安装包等!【[点击这里]】领取!
  • ① Python所有方向的学习路线图,清楚各个方向要学什么东西
  • ② 100多节Python课程视频,涵盖必备基础、爬虫和数据分析
  • ③ 100多个Python实战案例,学习不再是只会理论
  • ④ 华为出品独家Python漫画教程,手机也能学习

可以扫描下方二维码领取【保证100%免费在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/2301_78217634/article/details/147116627
今日推荐