2011-12-19 26 views
6

我試圖用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

這裏是結果:

Hermite Graph

問題是,在圖表的某些區域,該行向下。看數據,它永遠不會減少。我不知道算法是否應該這樣做,但是對於我正在處理的內容,我希望線條永遠不會向下(如果我手動繪製圖形,則無論如何我都不會讓它們向下指向) 。

所以,

  • 有什麼不對的圖形?
  • 算法是否應該這樣做?如果是這樣,有沒有發生這種情況?
  • 我已經嘗試了餘弦插值,但不喜歡它是如何結果。

下面是實際的繪圖功能:

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); 
    } 
} 
+0

嗨Snea,我想了解Cubic Hermite Spline是如何工作的。你能告訴我你怎麼稱呼你的HermiteInterpolate方法嗎? – Doro

回答

10

這是正常現象。

插值方法施加了一定的連續性條件,以便呈現平滑曲線的外觀。對於Hermite插值,沒有條件通過一系列遞增值的插值曲線也必須隨處增加,所以有時您會看到您在此處顯示的效果。

有些東西叫做monotone cubic interpolation,它可以做你想做的事情:如果數據點增加,插值曲線也會隨處增加。

+1

優秀!現在我只需要將所有這些步驟解釋爲代碼即可。 – Snea