我試圖用Cubic Hermite Splines繪製圖形。我從這個interpolation methods頁面抓取了簡單的代碼。Cubic Hermite樣條行爲奇怪
這是我的代碼:
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方法嗎? – Doro