是什么导致这个三次Bézier曲线方法的输出与计算器中绘制的不同?

2024-05-16 08:24:28 发布

您现在位置:Python中文网/ 问答频道 /正文

首先我要提到的是,因为我无法将数学符号on Wikipedia转换为代码,所以我从Rosetta Code*复制了这个方法,对其进行了重构,并使其成为生成器迭代器:

def cubic_bezier(t, p0, p1, p2, p3):
  x_0, y_0 = p0
  x_1, y_1 = p1
  x_2, y_2 = p2
  x_3, y_3 = p3
  while True:
    a = (1.0 - t) ** 3
    b = 3.0 * t * (1.0 - t) ** 2
    c = 3.0 * t ** 2 * (1.0 - t)
    d = t ** 3
    x = a * x_0 + b * x_1 + c * x_2 + d * x_3
    y = a * y_0 + b * y_1 + c * y_2 + d * y_3
    t = yield (x, y)

用法:

bc = cubic_bezier(0, (0, 4), (0, -1.35), (12.03, 2.59), (17, 0.1))
next(bc) # you call next once, then use generator.send(t) after https://stackoverflow.com/a/19302694/4178053

for i in range(18):
  print(f"t = {i}/17", bc.send(i/17))

输出:

t = 0/17 (0.0, 4.0)
t = 1/17 (0.12099328312639934, 3.1491186647669447)
t = 2/17 (0.46843069407693866, 2.4719112558518215)
t = 3/17 (1.0189985752086304, 1.9491797272542233)
t = 4/17 (1.7493832688784856, 1.5617260329737426)
t = 5/17 (2.6362711174435174, 1.2903521270099731)
t = 6/17 (3.656348463260737, 1.1158599633625073)
t = 7/17 (4.786301648687156, 1.0190514960309383)
t = 8/17 (6.0028170160797885, 0.9807286790148585)
t = 9/17 (7.282580907795644, 0.981693466313861)
t = 10/17 (8.602279666191738, 1.0027478119275395)
t = 11/17 (9.938599633625078, 1.0246936698554854)
t = 12/17 (11.268227152452678, 1.028332994097293)
t = 13/17 (12.567848565031547, 0.9944677386525546)
t = 14/17 (13.814150213718706, 0.9038998575208631)
t = 15/17 (14.983818440871158, 0.7374313047018115)
t = 16/17 (16.05353958884592, 0.4758640341949929)
t = 17/17 (17.0, 0.1)

预期产出:

t = 0/17 (0.0, 4.0) // same
t = 1/17 (0.12099328312639934, ~2)
t = 2/17 (0.46843069407693866, ~1.5)
t = 3/17 (1.0189985752086304, ~1.25)
t = 4/17 (1.7493832688784856, ~1.1)
t = 5/17 (2.6362711174435174, ~1)
t = 6/17 (3.656348463260737, ~1)
// the rest is the same
t = 7/17 (4.786301648687156, 1.0190514960309383)
t = 8/17 (6.0028170160797885, 0.9807286790148585)
t = 9/17 (7.282580907795644, 0.981693466313861)
t = 10/17 (8.602279666191738, 1.0027478119275395)
t = 11/17 (9.938599633625078, 1.0246936698554854)
t = 12/17 (11.268227152452678, 1.028332994097293)
t = 13/17 (12.567848565031547, 0.9944677386525546)
t = 14/17 (13.814150213718706, 0.9038998575208631)
t = 15/17 (14.983818440871158, 0.7374313047018115)
t = 16/17 (16.05353958884592, 0.4758640341949929)
t = 17/17 (17.0, 0.1)

screenshot of the cubic bezier curve graph from the graphing calculator Desmos

这是在线绘图计算器Desmos的屏幕截图,我用它绘制了一个三次Bézier曲线图,以便生成我的程序所需的任何参数/点,下面是它的永久链接:desmos.com/calculator/tc955zllcc

*(Rosetta Code是一个基于wiki的编程chrestomathy网站,在许多不同的编程语言中实现了各种编程问题的通用算法和解决方案。)


Tags: thecomsend编程codenextsamebc