简体   繁体   中英

math with very small numbers using float and double

I'm writing this code just to see the difference in the precision value while using a float and a double. basically I'm trying to calculate the value of reduced Plancks constant. Reduced Plancks const = Plancks const/2π.

#include<stdio.h>
#include<math.h>

const float H = 6.62607015e-34;
const float Pi = 3.1415926;
int main()
{
    float a = H / (2 * Pi);
    double b = H / (2 * Pi);
    printf("float is %ld \ndouble is %ld", a, b);
    return 0;
}

But the output does not make sense at all. I don't know what I'm doing wrong here.

float is 536870912
double is 954303911

I even tried to change the datatypes of the constants to double, which was no better.

float is 0
double is 954303911

I decreased the significant digits in the constant but it made no difference. Can anyone please tell me what I'm doing wrong here?

%ld is supposed to get a long int as argument, not double. Try %f , %e , %g , with additional modifiers at your option, or other formats supported by printf .

Moreover, you should consider enabling compiler warnings, for example -W -Wall with gcc:

: In function 'main':
:10:5: warning: format '%ld' expects argument of type 'long int', but argument 2 has type 'double' [-Wformat=]
     printf("float is %ld \ndouble is %ld", a, b);
     ^
:10:5: warning: format '%ld' expects argument of type 'long int', but argument 3 has type 'double' [-Wformat=]

The arguments have type double because float is promoted when used with a varargs function like printf .

In your example, the computations are basically the same: both H / (2 * Pi) computation are carried out as float, and after that the result is converted to double : in one case because b is double and in the other case due to promotion rules for printf .

printf("float is %ld \ndouble is %ld", a, b);

%d is the format specifier for integers, not floats. Use %f instead, it will work for double and because of automatic argument promotion, %f works also for float .

Most compilers would give a warning of this kind of error. Make sure you have warnings enabled in your compiler. For GCC, use -Wall -Wextra .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM