Skip to content

Commit bc2349b

Browse files
Merge pull request #329 from Candas1/faster_atan2
Faster atan2
2 parents 4d117ba + b780a45 commit bc2349b

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

src/common/foc_utils.cpp

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,33 @@ __attribute__((weak)) void _sincos(float a, float* s, float* c){
4444
*c = _cos(a);
4545
}
4646

47+
// fast_atan2 based on https://math.stackexchange.com/a/1105038/81278
48+
// Via Odrive project
49+
// https://github.com/odriverobotics/ODrive/blob/master/Firmware/MotorControl/utils.cpp
50+
// This function is MIT licenced, copyright Oskar Weigl/Odrive Robotics
51+
// The origin for Odrive atan2 is public domain. Thanks to Odrive for making
52+
// it easy to borrow.
53+
__attribute__((weak)) float _atan2(float y, float x) {
54+
// a := min (|x|, |y|) / max (|x|, |y|)
55+
float abs_y = fabsf(y);
56+
float abs_x = fabsf(x);
57+
// inject FLT_MIN in denominator to avoid division by zero
58+
float a = min(abs_x, abs_y) / (max(abs_x, abs_y));
59+
// s := a * a
60+
float s = a * a;
61+
// r := ((-0.0464964749 * s + 0.15931422) * s - 0.327622764) * s * a + a
62+
float r =
63+
((-0.0464964749f * s + 0.15931422f) * s - 0.327622764f) * s * a + a;
64+
// if |y| > |x| then r := 1.57079637 - r
65+
if (abs_y > abs_x) r = 1.57079637f - r;
66+
// if x < 0 then r := 3.14159274 - r
67+
if (x < 0.0f) r = 3.14159274f - r;
68+
// if y < 0 then r := -r
69+
if (y < 0.0f) r = -r;
70+
71+
return r;
72+
}
73+
4774

4875
// normalizing radian angle to [0,2PI]
4976
__attribute__((weak)) float _normalizeAngle(float angle){

src/common/foc_utils.h

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,11 @@ float _cos(float a);
7979
*/
8080
void _sincos(float a, float* s, float* c);
8181

82+
/**
83+
* Function approximating atan2
84+
*
85+
*/
86+
float _atan2(float y, float x);
8287

8388
/**
8489
* normalizing radian angle to [0,2PI]

0 commit comments

Comments
 (0)