Lana
Lana

Reputation: 31

How can I introduce a small number with a lot of significant figures into a C program?

I'm not particularly knowledgable about programming and I'm trying to figure out how to get a precise value calculated in a C program. I need a constant to the power of negative 7, with 5 significant figures. Any suggestions (keeping in mind I know very little, have never programmed in anything but c and only during required courses that I took years ago at school)?

Thanks!

Upvotes: 3

Views: 263

Answers (5)

user50049
user50049

Reputation:

long double offers the best precision in most cases and can be statically allocated and re-used to keep waste to a minimum. See also quadruple precision. Both change from platform to platform. Quadruple precision says the left most bit (1) continues to dictate signedness, while the next 15 bits dictate the exponent. IEEE 754 (i.e binary128) if the links provided aren't enough, they all lead back to long double :)

Simple shifting should take care of the rest, if I understand you correctly?

Upvotes: 0

Kragen Javier Sitaker
Kragen Javier Sitaker

Reputation: 1177

In the realm of computer floating-point formats, five significant digits is not a lot. The 32-bit IEEE-754 floating-point type used for float in most implementations of C has 24 bits of precision, which is about 7.2 decimal digits. So you can just use floating-point with no fear. double usually has 53 bits of precision (almost 16 decimal digits). Carl Smotricz's answer is fine, but there's also a pow function in C that you can pass -7.0 to.

There are times when you have to be careful about numerical analysis of your algorithm to ensure you aren't losing precision with intermediate results, but this doesn't sound like one of them.

Upvotes: 1

madmik3
madmik3

Reputation: 6973

you can use log to transform small numbers into larger numbers and do your math on the log transformed version. it's kind of tricky but it will work most of the time. you can also switch to python which does not have this problem as much.

Upvotes: -3

Carl Smotricz
Carl Smotricz

Reputation: 67760

You can get high-precision math from specialized libraries, but if all you need is 5 significant digits then the built-in float and double types will do fine. Let's go with double for maximum precision.

The negative 7th power is just 1 over your number to the 7th power, so...

double k = 1.2345678;  // your constant, whatever it is
double ktominus7 = 1.0 / (k * k * k * k * k * k * k);

...and that's it!

If you want to print out the value, you can do something like

printf("My number is: %9.5g\n", ktominus7);

Upvotes: 3

Ahmed Abdelkader
Ahmed Abdelkader

Reputation: 1735

For a constant value, the required calculation is going to be constant too. So, I recommend you calculate the value using your [desktop calculator / MATLAB / other] then hard-code it in your C code.

Upvotes: 2

Related Questions