1

I am trying to do a physics problem and need to store a value around 5 * 10-11; After trying float, long double and a few others none of them see to be long enough. Is there a data type that will allow me to do so? Thanks

long double I = 0;
I = 0.01902*pow(0.00318,3)/12;
printf("%Lf\n",I);

Output is 0.000000

Déjà vu
  • 28,223
  • 6
  • 72
  • 100
Jonski Goldstein
  • 169
  • 5
  • 16
  • 1
    Take a look at *arbitrary precision numbers*, e.g. in [this thread](http://stackoverflow.com/questions/1218149/arbitrary-precision-arithmetic-explanation) or [GNU MP](https://gmplib.org/). – Jens Apr 04 '16 at 00:42
  • 2
    What exactly makes you conclude that `float` or `long double` are not "long enough"? – Kurt Revis Apr 04 '16 at 00:44
  • IIRC, that value should be encoded correctly in an IEEE754 single-precision floating point number. – 3442 Apr 04 '16 at 00:44
  • 3
    Show us your code. You're probably screwing up your output formatting or something so the result just looks like it's zero. – user2357112 Apr 04 '16 at 00:47
  • Try `printf("%e\n", 5e-11)`. It seems to work, no? – 3442 Apr 04 '16 at 00:48
  • 1
    @Jonski: According to your edit, your problem is due to the precision you're printing the number in. Read about `printf()` format specifiers. – 3442 Apr 04 '16 at 00:52
  • @KemyLand Thanks man, just needed to put this as my print statement printf("%.15Lf\n",I); – Jonski Goldstein Apr 04 '16 at 00:55
  • http://stackoverflow.com/questions/16839658/printf-width-specifier-to-maintain-precision-of-floating-point-value – Déjà vu Apr 04 '16 at 00:59
  • What compiler are you using? Some of the Windows compilers mess up `long double` – M.M Apr 04 '16 at 02:38
  • Note that you are performing the calculation in `double` precision and then assigning the result to `long double`. To do the calculation in `long double` precision, put the `L` suffix on your constants, and call `powl` instead of `pow`. – M.M Apr 04 '16 at 02:43

1 Answers1

5
long double I = 0;
I = 0.01902*pow(0.00318,3)/12;

At this moment, I's value is approximately 5.096953e-11. Then...

printf("%Lf\n", I);

The sole format specifier in this printf() call is %Lf. This indicates that the argument is a long double (L), and that it should be printed as a floating-point number (f). Finally, as the precision (number of digits printed after the period) is not explicitly given, it is assumed to be 6. This means that up to 6 digits will be printed after the period.

There are several ways to fix this. Two of them would be...

printf(".15Lf\n", I);

This will set the precision to be 15. As such, 15 digits will be printed after the period. And...

printf("%Le\n", I);

This will print the number in scientific notation, that is, 5.096953e-11. It too can be configured to print more digits if you want them.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
3442
  • 8,248
  • 2
  • 19
  • 41