PDA

View Full Version : Quick C question

Apr 4, 2008, 06:58 AM
Hi Everyone,

I'm having some trouble dealing with large numbers in C. I'm reading in numbers in log format (eg 34 = 10^34), and using

y = pow(10, x);

to convert number x to the real value.

My numbers are typically 34-40 (so 10^34 - 10^40), and I keep getting infinities.

Anyone have any ideas?

Apr 4, 2008, 07:03 AM
Are they integers or real numbers?

If they are real numbers are you using float or double? I think you'll need double...

pilotError
Apr 4, 2008, 07:18 AM
What are you variables defined as?

I'm not sure about OS X, but linux has pow (double), powf (float) and powl (long).

#include <math.h>

int main(char * argv[], int argc) {

double x,y,z;
long lx,ly,lz;

z=10.0;
x=40.0;

y = pow(z, x);

printf("Double: %f ^ %f = %f\n", z, x, y);

lz=10;
lx=40;

ly = powl(lz, lx);

printf("Long: %ld ^ %ld = %ld\n", lz, lx, ly);

exit(0);
}

A quick test shows:

Double: 10.000000 ^ 40.000000 = 10000000000000000303786028427003666890752.000000
Long: 10 ^ 40 = -2147483648

Not sure if its right or not, I'm no math wiz... :o

One reason may be that a float / long are only 4 bytes. A double is 8 bytes.

Apr 4, 2008, 07:46 AM
10^40 should be 1 followed by 40 zeros. @ piloterror, OS X has powf and powl as well, check out man pow for more details.

lazydog
Apr 4, 2008, 09:44 AM
Hi Everyone,

I'm having some trouble dealing with large numbers in C. I'm reading in numbers in log format (eg 34 = 10^34), and using

y = pow(10, x);

to convert number x to the real value.

My numbers are typically 34-40 (so 10^34 - 10^40), and I keep getting infinities.

Anyone have any ideas?

Just had a quick look in float.h and found FLT_MAX_EXP and DBL_MAX_EXP defined. On my powerbook the maximum exponents are 38 for float and 308 for double. So it looks like you'll need to use doubles!

b e n

The