KalmanFilter.cs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. // 本程式碼由黃彥霖所有,轉載請註明出處 : https://blog.csdn.net/weixin_38884324
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using UnityEngine;
  5. public class KalmanFilter
  6. {
  7. public float[] Filter(float[] z)
  8. {
  9. float[] xhat = new float[z.Length];
  10. xhat[0] = z[0];
  11. float P = 1;
  12. for (int k = 1; k < xhat.Length; k++)
  13. {
  14. float xhatminus = xhat[k - 1];
  15. float Pminus = P + Q;
  16. float K = Pminus / (Pminus + R);
  17. xhat[k] = xhatminus + K * (z[k] - xhatminus);
  18. P = (1 - K) * Pminus;
  19. }
  20. return xhat;
  21. }
  22. bool isFirst = true;
  23. bool haveSetFirst = false;
  24. float xhat;
  25. float P;
  26. float z0;
  27. float Q = 1e-5f; // 0.00001
  28. float R = 0.0001f;
  29. public void SetFirst(float z0)
  30. {
  31. this.z0 = z0;
  32. haveSetFirst = true;
  33. }
  34. // 理想誤差
  35. public void SetQ(float Q)
  36. {
  37. this.Q = Q;
  38. }
  39. // 實際誤差
  40. public void SetR(float R)
  41. {
  42. this.R = R;
  43. }
  44. public float Filter(float z1)
  45. {
  46. if (isFirst)
  47. {
  48. isFirst = false;
  49. if (haveSetFirst == false) z0 = z1;
  50. xhat = z0;
  51. P = 1;
  52. }
  53. float xhatminus = xhat;
  54. float Pminus = P + Q;
  55. float K = Pminus / (Pminus + R);
  56. xhat = xhatminus + K * (z1 - xhatminus);
  57. P = (1 - K) * Pminus;
  58. return xhat;
  59. }
  60. public void Reset()
  61. {
  62. isFirst = true;
  63. haveSetFirst = false;
  64. xhat = 0;
  65. P = 0;
  66. z0 = 0;
  67. Q = 1e-5f; // 0.00001
  68. R = 0.0001f;
  69. }
  70. }