1. 程式人生 > >反距離加權插值方法——C#實現

反距離加權插值方法——C#實現

  正當自己無所事事時,朋友給我佈置了一項作業,如下圖:
  這裡寫圖片描述
  一乍聽,我還挺害怕的,以為很高深的問題,但因為給出了計算公式,實現起來並不難。將上圖中的公式拆解開來,並加上輸入、輸出功能基本上就算完成了。

輸入

  使用者需要輸入離散點個數n和相應的座標(x,y,z)、公式裡面的beta以及目標點的座標(x,y)
  根據計算需要,先設計點的資料結構:
  

        struct Point{
            public double x;
            public double y;
            public double z;
            public
double d; //該點距目標點的距離 public double w; //權重 }

宣告所需要的離散點陣列points、變數n和beta以及目標點point;

 /*全域性變數*/
 static Point[] points;  //使用者存放離散點
 static Point point = new Point();//目標點
 /*區域性變數*/
  int n=0;   //離散點個數
  int beta=1;   //beta值,一般設為1或2
/*資料輸入*/
 Console.Write("請輸入離散點個數n:");
 n = Convert.ToInt
32(Console.ReadLine()); w=new double[n]; points=new Point[n]; Console.Write("請輸入beta值(建議值1或2):"); beta = Convert.ToInt32(Console.ReadLine()); //下面輸入每一個離散點的座標 Console.WriteLine("****************\n下面輸入離散點座標(格式為:x,y,z:"); for(int i=0;i<n;i++){ Console.Write("第{0}個點座標:",i+1); string[]str1=Console.ReadLine
().Split(','); points[i].x=Convert.ToDouble(str1[0]); points[i].y=Convert.ToDouble(str1[1]); points[i].z=Convert.ToDouble(str1[2]); } //下面輸入要計算的點的座標 Console.Write("離散點輸入完成\n最後再輸入目標點的座標(格式為:x,y:\n目標點:"); string[] str2 = Console.ReadLine().Split(','); point.x = Convert.ToDouble(str2[0]); point.y = Convert.ToDouble(str2[1]); point.z = 0; //初始化為0

計算過程

  計算過程細分為三個小部分:
  1.計算各離散點至目標點的距離;
  2.計算權重;
  3.計算最終的高程值
 

//計算距離,每一個離散點至目標點的平面距離
static void GetDistance()
{
    for (int i = 0; i < points.Length; i++)
    {
        points[i].d = Math.Sqrt(Math.Pow((point.x - points[i].x), 2) + Math.Pow((point.y - points[i].y), 2));
    }
}
//獲取分母,計算中會用到
static double GetFenmu(int beta)
  {
      double fenmu = 0;
      for (int i = 0; i < points.Length; i++)
      {
          fenmu += Math.Pow((1/points[i].d),beta);
      }
      return fenmu;
  }

  //計算權重
  static void GetWeight(int beta)
  {
      //權重是距離的倒數的函式
      double fenmu = GetFenmu(beta);
      for (int i = 0; i < points.Length; i++)
      {
          points[i].w = Math.Pow((1 / points[i].d),beta) / fenmu;
      }
  }
 //得到最終高程值
 static void GetTargetZ()
 {
     for (int i = 0; i < points.Length; i++)
     {
         point.z += points[i].z * points[i].w;
     }
 }

結果輸出

  就是展示咯

//純粹為了展示
static void ShowPoints()
  {
      Console.WriteLine("計算結果:");
      Console.WriteLine("點號\tx\ty\tz\td\tw");
      for (int i = 0; i < points.Length; i++)
      {
          Console.WriteLine("No.{0}\t{1}\t{2}\t{3}\t{4}\t{5}", i + 1, points[i].x, points[i].y, points[i].z, points[i].d.ToString("#0.000"), points[i].w.ToString("#0.000"));
      }
  }

執行結果
下載