Skip to content

Commit 9630fb9

Browse files
committed
add better inverse square matrix
1 parent 5ae4084 commit 9630fb9

File tree

2 files changed

+24
-9
lines changed

2 files changed

+24
-9
lines changed

src/MadgwickAHRS.cpp

Lines changed: 23 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@
1313
// 29/09/2011 SOH Madgwick Initial release
1414
// 02/10/2011 SOH Madgwick Optimised for reduced CPU load
1515
// 19/02/2012 SOH Madgwick Magnetometer measurement is normalised
16+
// 08/07/2021 Added Better Fast Inverse Square Root Option
1617
//
1718
//=============================================================================================
1819

@@ -227,16 +228,29 @@ void Madgwick::updateIMU(float gx, float gy, float gz, float ax, float ay, float
227228
//-------------------------------------------------------------------------------------------
228229
// Fast inverse square-root
229230
// See: http://en.wikipedia.org/wiki/Fast_inverse_square_root
230-
231+
int instability_fix = 0; // 0 is original code
231232
float Madgwick::invSqrt(float x) {
232-
float halfx = 0.5f * x;
233-
float y = x;
234-
long i = *(long*)&y;
235-
i = 0x5f3759df - (i>>1);
236-
y = *(float*)&i;
237-
y = y * (1.5f - (halfx * y * y));
238-
y = y * (1.5f - (halfx * y * y));
239-
return y;
233+
if (instability_fix == 0){
234+
/* original code */
235+
float halfx = 0.5f * x;
236+
float y = x;
237+
long i = *(long*)&y;
238+
i = 0x5f3759df - (i>>1);
239+
y = *(float*)&i;
240+
y = y * (1.5f - (halfx * y * y));
241+
y = y * (1.5f - (halfx * y * y));
242+
return y;
243+
}
244+
else if (instability_fix == 1){
245+
/* close-to-optimal method with low cost from http://pizer.wordpress.com/2008/10/12/fast-inverse-square-root */
246+
unsigned int i = 0x5F1F1412 - (*(unsigned int*)&x >> 1);
247+
float tmp = *(float*)&i;
248+
return tmp * (1.69000231f - 0.714158168f * x * tmp * tmp);
249+
}
250+
else{
251+
/* optimal but expensive method: */
252+
return 1.0f / sqrtf(x);
253+
}
240254
}
241255

242256
//-------------------------------------------------------------------------------------------

src/MadgwickAHRS.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ class Madgwick{
3434
float yaw;
3535
char anglesComputed;
3636
void computeAngles();
37+
// int instability_fix;
3738

3839
//-------------------------------------------------------------------------------------------
3940
// Function declarations

0 commit comments

Comments
 (0)