Quick C question

Discussion in 'Mac Programming' started by seladore, Apr 4, 2008.

  1. macrumors newbie

    Joined:
    Mar 28, 2008
    #1
    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?
     
  2. macrumors G4

    Eraserhead

    Joined:
    Nov 3, 2005
    Location:
    UK
    #2
    Are they integers or real numbers?

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

    pilotError

    Joined:
    Apr 12, 2006
    Location:
    Long Island
    #3
    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.
     
  4. macrumors G4

    Eraserhead

    Joined:
    Nov 3, 2005
    Location:
    UK
    #4
    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.
     
  5. macrumors 6502a

    Joined:
    Sep 3, 2005
    Location:
    Cramlington, UK
    #5
    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
     
  6. macrumors G4

    Eraserhead

    Joined:
    Nov 3, 2005
    Location:
    UK
    #6
    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.
     
  7. macrumors newbie

    Joined:
    Apr 3, 2008
    #7
    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.
     

Share This Page