m5stack / M5StickC

M5StickC Arduino Library
MIT License
477 stars 222 forks source link

Fix compile warning(invSqrt) #42

Closed tanakamasayuki closed 5 years ago

tanakamasayuki commented 5 years ago

target warning

\Arduino\libraries\M5StickC\src\utility\MahonyAHRS.cpp: In function 'float invSqrt(float)':
\Arduino\libraries\M5StickC\src\utility\MahonyAHRS.cpp:244:20: warning: dereferencing type-punned pointer will break strict-aliasing rules [-Wstrict-aliasing]
  long i = *(long*)&y;
                    ^

\Arduino\libraries\M5StickC\src\utility\MahonyAHRS.cpp:246:16: warning: dereferencing type-punned pointer will break strict-aliasing rules [-Wstrict-aliasing]
  y = *(float*)&i;
                ^

Test Code

#include <M5StickC.h>

float invSqrtOld(float x) {
  float halfx = 0.5f * x;
  float y = x;
  long i = *(long*)&y;
  i = 0x5f3759df - (i>>1);
  y = *(float*)&i;
  y = y * (1.5f - (halfx * y * y));
  return y;
}

float invSqrtNew(float x) {
  typedef union {
    float f;
    long l;
  } union_t;

  float halfx = 0.5f * x;
  float y = x;
  long i = ((union_t*)&y)->l;
  i = 0x5f3759df - (i >> 1);
  y = ((union_t*)&i)->f;
  y = y * (1.5f - (halfx * y * y));
  return y;
}

void setup() {
  M5.begin();

  for ( float i = 0 ; i < 5 ; i += 0.5 ) {
    Serial.printf( "i = %f, invSqrt() = %f, invSqrtOld() = %f, invSqrtNew() = %f\n", i, invSqrt(i), invSqrtOld(i), invSqrtNew(i) );
  }

}

void loop() {
}

output

M5StickC initializing...OK
i = 0.000000, invSqrt() = 19817753709685768192.000000, invSqrtOld() = 19817753709685768192.000000, invSqrtNew() = 19817753709685768192.000000
i = 0.500000, invSqrt() = 1.413860, invSqrtOld() = 1.413860, invSqrtNew() = 1.413860
i = 1.000000, invSqrt() = 0.998307, invSqrtOld() = 0.998307, invSqrtNew() = 0.998307
i = 1.500000, invSqrt() = 0.815363, invSqrtOld() = 0.815363, invSqrtNew() = 0.815363
i = 2.000000, invSqrt() = 0.706930, invSqrtOld() = 0.706930, invSqrtNew() = 0.706930
i = 2.500000, invSqrt() = 0.631372, invSqrtOld() = 0.631372, invSqrtNew() = 0.631372
i = 3.000000, invSqrt() = 0.576847, invSqrtOld() = 0.576847, invSqrtNew() = 0.576847
i = 3.500000, invSqrt() = 0.534428, invSqrtOld() = 0.534428, invSqrtNew() = 0.534428
i = 4.000000, invSqrt() = 0.499154, invSqrtOld() = 0.499154, invSqrtNew() = 0.499154
i = 4.500000, invSqrt() = 0.471356, invSqrtOld() = 0.471356, invSqrtNew() = 0.471356