python绘制三次函数图像
时间: 2023-09-19 15:10:14 浏览: 208
要绘制三次函数 $y = ax^3 + bx^2 + cx + d$ 的图像,可以使用 Python 中的 matplotlib 库。具体步骤如下:
1. 导入 matplotlib 库:
```python
import matplotlib.pyplot as plt
```
2. 定义函数:
```python
def cubic_function(x, a, b, c, d):
return a * x**3 + b * x**2 + c * x + d
```
其中,`x` 是自变量,`a`、`b`、`c`、`d` 是函数的参数。
3. 生成 x 值序列:
```python
x = np.linspace(-5, 5, 100)
```
其中,`np.linspace(-5, 5, 100)` 表示在区间 $[-5, 5]$ 内生成 100 个等间距的点。
4. 计算 y 值序列:
```python
y = cubic_function(x, 1, -2, -3, 4)
```
其中,`cubic_function(x, 1, -2, -3, 4)` 表示使用函数 `cubic_function` 计算 x 值为 `x`,参数为 `(1, -2, -3, 4)` 的 y 值序列。
5. 绘制图像:
```python
plt.plot(x, y)
plt.xlabel('x')
plt.ylabel('y')
plt.title('Cubic Function')
plt.show()
```
其中,`plt.plot(x, y)` 表示绘制 x 值为 `x`,y 值为 `y` 的折线图;`plt.xlabel('x')` 和 `plt.ylabel('y')` 分别设置 x 轴和 y 轴的标签;`plt.title('Cubic Function')` 设置图像的标题;`plt.show()` 显示图像。
完整代码如下:
```python
import numpy as np
import matplotlib.pyplot as plt
def cubic_function(x, a, b, c, d):
return a * x**3 + b * x**2 + c * x + d
x = np.linspace(-5, 5, 100)
y = cubic_function(x, 1, -2, -3, 4)
plt.plot(x, y)
plt.xlabel('x')
plt.ylabel('y')
plt.title('Cubic Function')
plt.show()
```
阅读全文
相关推荐















