|
13 | 13 | // 29/09/2011 SOH Madgwick Initial release
|
14 | 14 | // 02/10/2011 SOH Madgwick Optimised for reduced CPU load
|
15 | 15 | // 19/02/2012 SOH Madgwick Magnetometer measurement is normalised
|
| 16 | +// 08/07/2021 Added Better Fast Inverse Square Root Option |
16 | 17 | //
|
17 | 18 | //=============================================================================================
|
18 | 19 |
|
@@ -227,16 +228,29 @@ void Madgwick::updateIMU(float gx, float gy, float gz, float ax, float ay, float
|
227 | 228 | //-------------------------------------------------------------------------------------------
|
228 | 229 | // Fast inverse square-root
|
229 | 230 | // See: http://en.wikipedia.org/wiki/Fast_inverse_square_root
|
230 |
| - |
| 231 | +int instability_fix = 0; // 0 is original code |
231 | 232 | 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 | + } |
240 | 254 | }
|
241 | 255 |
|
242 | 256 | //-------------------------------------------------------------------------------------------
|
|
0 commit comments