Go Down

Topic: Inaccurate trig constant definitions in wiring.h (Read 1 time) previous topic - next topic


The following constants are defined in "wiring.h"

#define PI 3.14159265
#define HALF_PI 1.57079
#define TWO_PI 6.283185
#define DEG_TO_RAD 0.01745329
#define RAD_TO_DEG 57.2957786

Getting acceptable acuracy with trig math using the float math library can be quite a challenge and it does not help if one starts out with inaccurate or low precision constants.

The "float" data type supports 7+ digits of accuracy (24 bit mantissa + 8 bit exponent) so a minimum of 8 significant digits should be used when defining constants. Also I expect gcc will use double precision for intermediate compile time calculations so there is some benefit to adding digits up to full double even though float will be used for runtime math. Also above the last two digits of RAD_TO_DEG are off.

I suggest the definitions should be substituted with the full glory of double precision as follows:

#define PI 3.1415926535897932384626433832795
#define HALF_PI 1.5707963267948966192313216916398
#define TWO_PI 6.283185307179586476925286766559
#define DEG_TO_RAD 0.017453292519943295769236907684886
#define RAD_TO_DEG 57.295779513082320876798154814105


It would be interesting to see the difference in the ouput you get with the more precise constants. If you get a chance, can you post the results of both versions.


I apologize if there is a logical explanation, but why do we opt for #define, and not const float?
Code: [Select]
const float PI = 3.1415926535897932384626433832795;


May 10, 2009, 01:03 am Last Edit: May 10, 2009, 01:08 am by mikalhart Reason: 1
> why do we opt for #define, and not const float?

const float PI = 3.1415926535897932384626433832795;

Well, for one thing, that "float" expression just eliminated all the extra precision that the original poster was asking for. :)

Of course, in Arduino-land, a double and a float are the same (4 bytes of precision only), so the extra precision won't help anyway.

Go Up