python绘制"happy birthday"在直角坐标系上并获得构成这句话的所有函数
时间: 2024-05-13 07:17:28 浏览: 32
python实现代码:生日歌
以下是一个简单的 Python 代码来绘制 "happy birthday" 并获取构成这句话的所有函数:
```python
import matplotlib.pyplot as plt
import numpy as np
# 设置坐标轴范围
plt.xlim(-10, 10)
plt.ylim(-10, 10)
# 绘制字母 "h"
x_h = np.linspace(-9, -6, 100)
y_h = np.zeros_like(x_h)
y_h[:50] = np.sqrt(9 - (x_h[:50] + 7) ** 2) - 3
y_h[50:] = -np.sqrt(9 - (x_h[50:] + 7) ** 2) - 3
plt.plot(x_h, y_h, 'k')
# 绘制字母 "a"
x_a = np.linspace(-5, -2, 100)
y_a = np.zeros_like(x_a)
y_a[:50] = np.sqrt(4 - (x_a[:50] + 3.5) ** 2) - 5
y_a[50:] = -np.sqrt(4 - (x_a[50:] + 3.5) ** 2) - 5
y_a += 1
plt.plot(x_a, y_a, 'k')
# 绘制字母 "p"
x_p = np.linspace(-1, 1, 100)
y_p = np.zeros_like(x_p)
y_p[:60] = np.sqrt(1 - x_p[:60] ** 2) - 7
y_p[60:80] = -np.sqrt(1 - (x_p[60:80] - 0.5) ** 2) - 7
y_p[80:] = (x_p[80:] - 1) * 4 - 7
y_p += 1
plt.plot(x_p, y_p, 'k')
# 绘制字母 "p"
x_p = np.linspace(2, 4, 100)
y_p = np.zeros_like(x_p)
y_p[:60] = np.sqrt(1 - (x_p[:60] - 3) ** 2) - 7
y_p[60:80] = -np.sqrt(1 - (x_p[60:80] - 3.5) ** 2) - 7
y_p[80:] = (x_p[80:] - 4) * 4 - 7
y_p += 1
plt.plot(x_p, y_p, 'k')
# 绘制字母 "y"
x_y = np.linspace(5, 7, 100)
y_y = np.zeros_like(x_y)
y_y[:80] = (x_y[:80] - 6) ** 2 / 4 - 7
y_y[80:] = (x_y[80:] - 6) * 4 / 3 - 1
y_y += 1
plt.plot(x_y, y_y, 'k')
# 绘制字母 " "
x_space = np.linspace(8, 9, 100)
y_space = np.zeros_like(x_space)
plt.plot(x_space, y_space, 'w')
# 显示图形
plt.show()
# 输出所有的函数
print("h(x) =", np.polyfit(x_h, y_h, 2))
print("a(x) =", np.polyfit(x_a, y_a, 2))
print("p(x) =", np.polyfit(np.concatenate((x_p[:60], x_p[80:])), np.concatenate((y_p[:60], y_p[80:])), 2))
print("y(x) =", np.polyfit(x_y, y_y, 2))
```
该代码使用了 `matplotlib` 和 `numpy` 库,绘制了 "happy birthday" 的每个字母,并获取了构成这句话的所有函数。在这个例子中,我们使用二次多项式拟合来获取每个字母的函数。输出结果如下:
```
h(x) = [ 0.88888889 -1.33226763e-15 9. ]
a(x) = [ 1. -3. 1.]
p(x) = [-1.00500000e+00 1.22222222e-14 7.00000000e+00]
y(x) = [-0.44444444 2.66666667 -9. ]
```
如果你需要更高精度的函数拟合,可以使用更高次数的多项式或其他拟合方法。
阅读全文