欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

Python+Matplotlib 显示通用函数、变换和函数的简单示例

最编程 2024-10-03 19:53:37
...


import numpy as np
import matplotlib.pyplot as plt

# 设置中文字体
plt.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False  # 用来正常显示负号

# 创建子图
fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(15, 5))

# 1. 函数示例:f(x) = x^2
x = np.linspace(-2, 2, 100)
y = x**2

ax1.plot(x, y)
ax1.set_title('函数: f(x) = x^2')
ax1.set_xlabel('x')
ax1.set_ylabel('y')
ax1.grid(True)

# 2. 变换示例:g(x) = 2f(x) + 1
y_transformed = 2*y + 1

ax2.plot(x, y, label='原函数')
ax2.plot(x, y_transformed, label='变换后')
ax2.set_title('变换: g(x) = 2f(x) + 1')
ax2.set_xlabel('x')
ax2.set_ylabel('y')
ax2.legend()
ax2.grid(True)

# 3. 泛函示例:计算函数在区间[-1,1]上的平均值
def functional(f, a, b):
    x_vals = np.linspace(a, b, 1000)
    y_vals = f(x_vals)
    return np.mean(y_vals)

f_values = [x**2, x**3, np.sin(x), np.cos(x)]
f_names = ['x^2', 'x^3', 'sin(x)', 'cos(x)']
averages = [functional(lambda x: f, -1, 1) for f in f_values]

ax3.bar(f_names, averages)
ax3.set_title('泛函: 函数在[-1,1]上的平均值')
ax3.set_ylabel('平均值')
ax3.grid(True)

plt.tight_layout()
plt.show()

推荐阅读