【发布时间】:2012-01-23 08:00:08
【问题描述】:
我正在尝试使用Cubic Hermite Splines 绘制图表。我从interpolation methods 页面获取了执行此操作的简单代码。
这是我的代码:
private float HermiteInterpolate(float y0, float y1, float y2, float y3, float mu)
{
var mu2 = mu * mu;
var a0 = -0.5f * y0 + 1.5f * y1 - 1.5f * y2 + 0.5f * y3;
var a1 = y0 - 2.5f * y1 + 2f * y2 - 0.5f * y3;
var a2 = -0.5f * y0 + 0.5f * y2;
var a3 = y1;
return (a0 * mu * mu2) + (a1 * mu2) + (a2 * mu) + a3;
}
有了这些数据(y 值,从 0 到 1,x 值从 0 到 21 均匀分布):
0, 0.09448819, 0.1102362, 0.1338583, 0.1811024, 0.2283465 ,0.3543307, 0.4645669, 0.480315, 0.480315, 0.527559, 0.527559, 0.527559, 0.527559, 0.527559, 0.527559, 0.6062992, 0.6377953, 0.6377953, 0.6377953, 0.7480315
结果如下:
问题是,在图表的某些区域,线向下。查看数据,它从未减少。我不知道算法是否应该这样做,但对于我正在做的事情,我希望线条永远不会向下(如果我是手工绘制图表,我永远不会让它们指向下方) .
所以,
- 图形有问题吗?
- 算法应该这样做吗?如果是这样,有没有这种情况不会发生?
- 我尝试过余弦插值,但结果不喜欢。
这是实际的绘图功能:
public void DrawGraph(IList<float> items)
{
for (var x = 0; x < Width; x++)
{
var percentThrough = (float)x / (float)Width;
var itemIndexRaw = items.Count * percentThrough;
var itemIndex = (int)Math.Floor(itemIndexRaw);
var item = items[itemIndex];
var previousItem = (itemIndex - 1) < 0 ? item : items[itemIndex - 1];
var nextItem = (itemIndex + 1) >= items.Count ? item : items[itemIndex + 1];
var nextNextItem = (itemIndex + 2) >= items.Count ? nextItem : items[itemIndex + 2];
var itemMu = FractionalPart(itemIndexRaw);
var pointValue = HermiteInterpolate(previousItem, item, nextItem, nextNextItem, itemMu);
WritePixel(x, (int)(pointValue * Height) - 1, (1 - FractionalPart(pointValue)), false);
WritePixel(x, (int)(pointValue * Height), 1.0f, false);
WritePixel(x, (int)(pointValue * Height) + 1, FractionalPart(pointValue), false);
}
}
【问题讨论】:
-
嗨 Snea,我正在尝试了解 Cubic Hermite Spline 的工作原理。你能告诉我你是怎么调用 HermiteInterpolate 方法的吗?