Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

seladore

macrumors newbie
Original poster
Mar 28, 2008
17
0
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

macrumors G4
Nov 3, 2005
10,434
12,250
UK
Are they integers or real numbers?

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

pilotError

macrumors 68020
Apr 12, 2006
2,237
4
Long Island
What are you variables defined as?

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

Code:
#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... :eek:

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

Eraserhead

macrumors G4
Nov 3, 2005
10,434
12,250
UK
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

macrumors 6502a
Sep 3, 2005
709
6
Cramlington, UK
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

macrumors G4
Nov 3, 2005
10,434
12,250
UK
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

macrumors newbie
Apr 3, 2008
8
0
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.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.