0

I have a question,maybe it's stupid.I wrote that code to calculate expontiation :

#include<stdio.h>

int i=0;
float power(int a,int b);
main()
{     int base,exp;
      printf("Base:\n");
      scanf("%d",&base);
      printf("Exp:\n");
      scanf("%d",&exp);
      power(base,exp);
      system("pause");
      }
float power(int a,int b)
{     float result=1;
      for (i=0;i<b;i++)
      {
          result=result*a;
          }
      printf("result = %lf \n",result);
      }

What got me confused was that i gave as input base=2 and exp=100 and the output was correct.The thing i don't understand is how does the program calculates the correct number even though float type is 4byte=32 bits,which means that the greatest number a float(result) variable can get is 2^32-1<<2^100

1 Answers1

2

You need to understand how floating point numbers are stored. In contrast to fixed point numbers, in floating point numbers, the decimal is floating. So although the precision of floating point number is finite or limited, but it can store much larger range of data than it appears.

For example(just an analogy to understand how things work. For actual understanding please refer to the floating point number link I shared in previous paragraph) if you have 3 digits to represent number, using fixed point you can represent number from 0 to 999(least count is 1). But if you use 2 digits for number and third digit for (exponent-1), you can represent from 0 to 99x109(Variable least count).

Mohit Jain
  • 30,259
  • 8
  • 73
  • 100
  • you're right,i checked my book from the c.architecture course i had last semester and i remembered what you mean,thanks!! Also,don't you mean 99^9 instead 99^10? –  May 20 '14 at 12:27
  • You can assume 99^9, it is just to give an idea. My point was, there is no point of keeping `0` as exponent as anything to power 0 is 1. And keeping multiple representations of `1` would be bad. So instead I stored (exponent-1) which means exponent varies from (1-10) but stored in digit as (0-9). Even my scheme is faulty as there are multiple representations of 0. (0 to power anything is 0). But it is just an analogy to visualize things better. – Mohit Jain May 20 '14 at 12:29