PDA

View Full Version : Quick C question




seladore
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?



Eraserhead
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.

Eraserhead
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

Eraserhead
Apr 4, 2008, 10:50 AM
On this topic on Macs in general int is the same as long, but normally on other platforms int only goes up to 32768, whereas long goes up to 2 billion odd.

litesgod
Apr 4, 2008, 11:22 AM
Not sure what the final outcome is for the values, but large numbers in C can be difficult to work with. What I would consider doing is just keeping the values in exponent form. Manipulate the exponents according to the law of exponents instead of trying to convert them into large numbers. The only challenge is if you need to add/subtract the values, and given everything is a base of 10, that should be possible to do as well.