-
Notifications
You must be signed in to change notification settings - Fork 0
/
Kalman.cpp
57 lines (49 loc) · 1.48 KB
/
Kalman.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
double frand()
{
return 2 * ( ( rand() / ( double ) RAND_MAX ) - 0.5 ); //随机噪声
}
int main ( int argc, char* argv[] )
{
( void ) argc;
( void ) argv;
float x_last = 0;
float p_last = 0.02;
float Q = 0.018;
float R = 0.542;
float kg;
float x_mid;
float x_now;
float p_mid;
float p_now;
float z_real = 0.56;
float z_measure;
float summerror_kalman = 0;
float summerror_measure = 0;
int i;
x_last = z_real + frand() * 0.03;
x_mid = x_last;
for ( i = 0; i < 2000; i++ )
{
x_mid = x_last;
p_mid = p_last + Q;
kg = p_mid / ( p_mid + R );
z_measure = z_real + frand() * 0.03; //测量值
x_now = x_mid + kg * ( z_measure - x_mid ); //估计出的最有值
p_now = ( 1 - kg ) * p_mid; //最优值对应的协方差
printf ( "Real position:%6.3f\n", z_real );
printf ( "Measure position:%6.3f [diff:%.3f]\n", z_measure, fabs ( z_real - z_measure ) );
printf ( "Kalman position: %6.3f [diff:%.3f]\n", x_now, fabs ( z_real - x_now ) );
printf ( "\n\n" );
summerror_kalman += fabs ( z_real - x_now );
summerror_measure += fabs ( z_real - z_measure );
p_last = p_now;
x_last = x_now;
}
printf ( "total error :%f\n", summerror_measure );
printf ( "total kalman error :%f\n", summerror_kalman );
printf ( "pesent kalman error:%d%%\n", 100 - ( int ) ( ( summerror_kalman / summerror_measure ) * 100 ) );
getchar();
}