Projectitis
Well-known member
Hi all,
I found this fast "pow" approximation function for floats:
There is also this related fastPow for doubles (which I haven't tried as I'm working with floats):
here is an example where I am raising 2 to the power of a random number 1 <= 10 (just for testing - I realise bit shifting is much faster).
fastPow (incorrect) is on the left and pow (correct) on the right.
I realise that fastPow is only an approximation and will have error, but the results I'm getting are wildly inaccurate.
Does anyone have any idea why fastPow is not working? Could it be an endian issue?
Full code to reproduce:
I found this fast "pow" approximation function for floats:
Code:
inline float fastPow(float a, float b) {
union {
float d;
int x;
} u = { a };
u.x = (int)(b * (u.x - 1072632447) + 1072632447);
return u.d;
}
There is also this related fastPow for doubles (which I haven't tried as I'm working with floats):
Code:
inline double fastPow(double a, double b) {
union {
double d;
int x[2];
} u = { a };
u.x[1] = (int)(b * (u.x[1] - 1072632447) + 1072632447);
u.x[0] = 0;
return u.d;
}
here is an example where I am raising 2 to the power of a random number 1 <= 10 (just for testing - I realise bit shifting is much faster).
fastPow (incorrect) is on the left and pow (correct) on the right.
Code:
2.00 2.00
2.26 4.00
3.32 64.00
2.53 8.00
2.26 4.00
2.26 4.00
2.00 2.00
3.85 256.00
4.23 512.00
2.26 4.00
3.06 32.00
2.00 2.00
3.59 128.00
I realise that fastPow is only an approximation and will have error, but the results I'm getting are wildly inaccurate.
Does anyone have any idea why fastPow is not working? Could it be an endian issue?
Full code to reproduce:
Code:
#include <Math.h>
inline float fastPow(float a, float b) {
union {
float d;
int x;
} u = { a };
u.x = (int)(b * (u.x - 1072632447) + 1072632447);
return u.d;
}
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
delay(1000);
uint32_t i;
float f, ans;
Serial.println(F("Compare: fastPow, pow"));
for (i=0; i<100; i++){
f = random(1,11);
ans = fastPow( 2, f );
Serial.print(ans);
Serial.print(F(" "));
ans = pow( 2, f );
Serial.println(ans);
}
}
void loop() {
// put your main code here, to run repeatedly:
delay(100);
}