[英]How can I generate numbers between x and n with a curve with Python?
I'm trying to generate a non-linear curve between two integers, let's say 0 and 25 that matches up to this curve here: 我试图在两个整数之间生成非线性曲线,假设0和25匹配此曲线:
It seems like a stupid simple problem, the curve I need even looks like part of a circle, so generating a large circle, and taking the points at the bottom right would solve this, but I don't know how to do any of that. 这似乎是一个愚蠢的简单问题,我需要的曲线甚至看起来像一个圆圈的一部分,所以生成一个大圆圈,并采取右下角的点将解决这个问题,但我不知道如何做任何这个。
All I need is a list from 0 to 25 with the curve as a part of that list, if that makes sense. 我需要的是一个从0到25的列表,曲线作为该列表的一部分,如果这是有道理的。 Starting slowly increasing, then speeding up, then slowing down near the end.
开始慢慢增加,然后加速,然后在接近结束时放慢速度。
I've tried this with a similar result, but it's not at the exact angle/curve. 我尝试了类似的结果,但它不是精确的角度/曲线。
x=[]
y=range(25)
for i in range(25):
x.append((i**.25)**2)
plt.plot(x, y)
plt.show()
Thanks 谢谢
If you really want to have the same curve, you could load the plot image, and use PIL to get every blue pixel: 如果你真的想拥有相同的曲线,可以加载绘图图像,并使用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)
Then, knowing that (0, 20) in the plot is the pixel (63, 355), and (25, 160) in the plot is the pixel (516, 32), you can transform pixel coordinates to data points: 然后,知道图中的(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]
Finally, you can use numpy polyfit to get a polynomial fit to the points you previously obtained: 最后,您可以使用numpy polyfit来获得与先前获得的点的多项式拟合:
>>> np.polyfit(X, Y, 3)
[ 8.23918277e-03 -7.33330644e-02 2.60046715e+00 2.03012850e+01]
And then, plot the result using poly1d
to get a function that given a x
value returns its y
value: 然后,使用
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.