![](/img/trans.png)
[英]How to Generate N random numbers in Python 3 between 0 to infinity
[英]How can I generate numbers between x and n with a curve with Python?
如果你真的想擁有相同的曲線,可以加載繪圖圖像,並使用PIL獲取每個藍色像素:
from urllib.request import urlopen
from PIL import Image
img = Image.open(urlopen('https://i.stack.imgur.com/NpiMq.png'))
X = []
Y = []
for x in range(img.size[0]):
for y in range(img.size[1]):
r, g, b, a = img.getpixel((x, y))
if b > r and b > g:
X.append(x)
Y.append(y)
然后,知道圖中的(0,20)是像素(63,355),並且圖中的(25,160)是像素(516,32),您可以將像素坐標轉換為數據點:
X = [(x - 63) * (25 - 0) / (516 - 63) + 0 for x in X]
Y = [(y - 355) * (160 - 20) / (32 - 355) + 20 for y in Y]
最后,您可以使用numpy polyfit來獲得與先前獲得的點的多項式擬合:
>>> np.polyfit(X, Y, 3)
[ 8.23918277e-03 -7.33330644e-02 2.60046715e+00 2.03012850e+01]
然后,使用poly1d
繪制結果以獲取給定x
值返回其y
值的函數:
import numpy as np
from matplotlib import pyplot as plt
x2y = np.poly1d(np.polyfit(X, Y, 3))
new_X = [x / 10 for x in range(250)]
new_Y = [x2y(x) for x in new_X]
plt.plot(new_X, new_Y)
plt.show()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.