Search code examples
ctypesprecision

How to change the precision of a floating point in C at runtime?


How to make a variable float complex or double complex depending on user input? I'm trying to plot the Mandelbrot set and I have the same long code for float and double but in some cases float is not precise enough and double is too slow. I'm running it on a low-performance calculator, so float is less than 1 second and double takes at least 5 seconds. I'd like to let the user choose precision over speed or speed over precision. I would like to get something like this:

int user_input;
scanf("%d", &user_input);

switch (user_input) {
      case 0:
          float z;
          float c;
          break;
      case 1:
          double z;
          double c;
          break;
}
for(int i=0;i<1920;i++){
    for(int j=0;j<1080;j++){
        z=0.0+0.0*I;
        c=(i+j*I)/Zoom
}}

Expected outcome: if the user types 0, then all the calculations are performed using floats, and if the user types 1, the calculations are performed using doubles.

But this throws error: conflicting types for ‘z’; have ‘double’, previous declaration of ‘z’ with type ‘float’.

Is something like this possible in C?

I tried making two different varables for float and double but changing them in all the code (I have way more code) would be long and tedious.


Solution

  • The only viable solution on modern systems which supports dynamic linking is to compile one version of your program using float and another using double. Then the main program will load the correct version of the dynamic library and it will execute the requested version.