Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compile c code with float instead of double

I have a lengthy numeric integration scheme written in C. I'd like to test my algorithm in floating point precision. Is there a way to tell gcc to demote every occurrence of double to float in the entire program?

like image 655
hanno Avatar asked Jul 11 '14 01:07

hanno


People also ask

Can I use float instead of double?

Double is more precise than float and can store 64 bits, double of the number of bits float can store. Double is more precise and for storing large numbers, we prefer double over float. For example, to store the annual salary of the CEO of a company, double will be a more accurate choice.

Should I use float or double in C?

The default choice for a floating-point type should be double . This is also the type that you get with floating-point literals without a suffix or (in C) standard functions that operate on floating point numbers (e.g. exp , sin , etc.).

Why do we typically use float instead of double?

double has higher precision, whereas floats take up less memory and are faster. In general you should use float unless you have a case where it isn't accurate enough. On typical modern computers, double is just as fast as float.


1 Answers

You can't safely do this without modifying your source code, but that shouldn't be terribly difficult to do.

Using the preprocessor to force the keyword double in your program to be treated as float is a bad idea; it will make your program difficult to read, and if you happen to use long double anywhere it would be treated as long float, which is a syntax error.

As stix's answer suggests, you can add a typedef, either at the top of your program (if it's a single source file) or in some header that's #includeed by all the relevant source files:

typedef double real; /* or pick a different name */

Then go through your source code and change each occurrence of double to real. (Be careful about doing a blind global search-and-replace.)

Make sure that the program still compiles, runs, and behaves the same way after this change. Then you can change the typedef to:

 typedef float real;

and recompile to use float rather than double.

It's not quite that simple, though. If you're using functions declared in <math.h>, you'll want to use the right function for whatever floating-point type you're using; for example, sqrt() is for double, sqrtf() is for float, and sqrtl() is for long double.

If your compiler supports it, you might use the <tgmath.h> header, which defines type-generic macros corresponding to the math functions from <math.h>. If you use <tgmath.h>, then sqrt(x) will resolve to call the correct square root function depending on the type of the argument.

like image 177
Keith Thompson Avatar answered Oct 15 '22 18:10

Keith Thompson