![見出し画像](https://assets.st-note.com/production/uploads/images/121867255/rectangle_large_type_2_14f735bfdfde5af2abfab7bf65df2560.png?width=800)
【Python】素数のらせんを描いてみた
先日以下の記事で、ちょっとした「数学アート」を紹介しました。
今年から勉強しているPythonというプログラミング言語。
仕事でPythonのmatplotlib(グラフ描画ライブラリ)に触れる機会があり、調子に乗って自分でこのらせんを描いてみました。
紹介した動画のようなアニメーションではないですが、
素数を極座標にプロットするだけならたった20行で描けちゃいます。
(最後にソースコード置いておきます)
以下、10のn乗(n=2~7)以下の素数を全てプロットしたグラフです。
一番下でも描画速度1秒以下。いろんな意味でヤバいです。
![](https://assets.st-note.com/img/1700122459573-JQpMI3DnBx.png?width=800)
![](https://assets.st-note.com/img/1700122470239-ecGrHRziT4.png?width=800)
![](https://assets.st-note.com/img/1700122482282-GXcGPKNB5G.png?width=800)
![](https://assets.st-note.com/img/1700122531869-QJIfbPeDiB.png?width=800)
![](https://assets.st-note.com/img/1700122501682-9rburd8WpC.png?width=800)
![](https://assets.st-note.com/img/1700122549341-0dPeoWfaZR.png?width=800)
ソースコードです。お遊びコードなのでコメントも何もないです。
Python万能すぎる・・・
import matplotlib.pyplot as plt
import numpy as np
from sympy import sieve
n = 10**5
p = np.array([i for i in sieve.primerange(2, n)])
x = p * np.cos(p)
y = p * np.sin(p)
scale = 5
ratio = 2
width = np.max(p)
fig, ax = plt.subplots(facecolor="black", figsize=(ratio*scale,scale))
ax.axis("off")
ax.set_xlim(-width,width)
ax.set_ylim(-width/ratio, width/ratio)
ax.scatter(x,y,s=1,c="yellow")
plt.title("num of primes: {}".format(len(p)),c="white")
plt.show()
![](https://assets.st-note.com/img/1700128257043-Qqe4y56gBu.png?width=800)
頂いたサポートは、クリエイターとしての活動費として使用させていただきます!