# Floating Point Constants

This topic is 2178 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

(in c++)

In my code I have a special type that allows me to switch between 'float' and 'double' for at least some portions of the code.

The problem is constants like '0.015' are default double, and generate tonnes of warnings when I switch to 'float' mode. Because of expressions like 'floatn = 1.5'. However, if I append an 'f' to the end of every constant then I could be removing some of the accuracy benefits of doubles in double mode.

What should I do to get rid of these warnings and still allow me to have the benefit of doubles when I compile it with 'floatn' typedef'd to 'float'?

Thank!

##### Share on other sites
(Rusty C++) Can you use an ifdef conditional block to define them in the proper format?

##### Share on other sites
Definitely, however that would create thousands of ugly ifdefs in my application so a more elegant solution is called for.

##### Share on other sites
You could explicitly cast it like:
[source lang="cpp"]#ifdef FLOAT_SUPPORT==1
#define MyFloat(x) float(x)
#else
#define MyFloat(x) double(x)
#end

#define MyConst MyFloat(1.23)

[/source]

##### Share on other sites
You could do something like this:
#define USE_FLOAT #ifdef USE_FLOAT typedef float Real; #define CREAL(x) x ## f #else typedef double Real; #define CREAL(x) x #endif const Real PI = CREAL(3.14);

##### Share on other sites
Then refactor your code so that it's not full of magic numbers?

Create a function that returns the proper data type, and use an ifdef to define it? Feed it a string, and it will return either a float or a double, depending on your definitions.

edit: Wow, ninja'd Edited by Daaark

##### Share on other sites

Then refactor your code so that it's not full of magic numbers?

I try not to use magic numbers, the vast majority of the warnings come from initialization and simple arithmetic.

Thanks everyone I'll give your ideas a shot, but I'm still open to more suggestions!

##### Share on other sites

Well then it seems highly unlikely you need to worry about loss of precision when converting from float to double, unless your simple arithmetic involves numbers like 23423.4234234098029384233409583405

Of course, do note that simple decimal expressions like "0.3" have an infinite number of digits in binary fraction form and will suffer additional rounding if coerced to float.

##### Share on other sites
[source]
typedef float real; // or double

real x = real(23.0);
[/source]

I'm not sure why that didn't occur to me last night...

And yeah I'm being anal about precision even though its hardly an issue but it helps for arithmetic with pi or simply 1/3 like the above poster said. Edited by James Leighe

1. 1
2. 2
3. 3
Rutin
22
4. 4
JoeJ
16
5. 5

• 14
• 29
• 13
• 11
• 11
• ### Forum Statistics

• Total Topics
631774
• Total Posts
3002290
×