Search code examples
cmatlabfloating-accuracydigits

Exponential limits for C and Matlab


In computers, the math operation of floating numbers is actually processed using the base number and the exponential number separately, and then combine them together. We learn this in our computation fundamental textbooks. However, I find the limits in C program and MATLAB are quite different. Here is an example:

C program:

#include <stdio.h>

int main()
{
    float c1, c2, c3;
    
    c1 = 1.0e-20;
    c2 = 1.0e-30;
    
    c3 = c1 * c2;
    printf("%e,%e,%e\n",c1,c2,c3);

    return 0;
}

The running result is:

1.000000e-20,1.000000e-30,0.000000e+00

MATLAB program:

c1 = 1.0e-20;
c2 = 1.0e-30;
    
c3 = c1 * c2;
fprintf("%e,%e,%e\n",c1,c2,c3);

The running result is:

1.000000e-20,1.000000e-30,1.000000e-50

It is obvious that MATLAB gives the right multiplication result, whereas C gives a wrong result. Could anyone answer why this happens?

In my project, my computation involves such small number computations in C language. Since Matlab can do it correctly, can you give a suggestion how I can also do this in C?


Solution

  • In most languages, you'll have access to at least two floating-point types: single-precision and double-precision.

    In C, float is a single-precision float, double is a double-precision float.

    MATLAB uses double by default, but also has single for single-precision floats.

    If you use single values in your MATLAB program, you'll do the same computation that your C program does, with the same result:

    c1 = single(1.0e-20);
    c2 = single(1.0e-30);
    c3 = c1 * c2;
    fprintf("%e,%e,%e\n",c1,c2,c3);
    

    The output is:

    1.000000e-20,1.000000e-30,0.000000e+00
    

    Likewise, you can change your C program to use double instead of float, to reproduce the MATLAB results exactly.